I have a server which I need to login many users to. During each login the server has to do lots of things that take a while like make requests to other servers/databases and wait for them. So whilst one user is logging in I would like the other users to start logging in too.
I have tried to figure out how the asyncio module works but have not found any code that does what I want it to do.
Note: I am using python 3.6 so some of the asyncio features are different to 3.7.
import asyncio
import requests
class user:
def __init__(self, port):
# Create user here
self.port=port
self.data = requests.get(someURL,port)
async def login(self,email):
# Step 1 of logging in
requsts.post(someURL, self.port, email) # Logs them in but takes a while to process everything
while True:
data = requests.get(someURL, self.port)# Gets data from server
if data.connected == True:
break
else:
pass
#Go onto logging in next user while we wait for the server to do things
# Step 2 of logging in
requests.post(someURL, self.port, email)
while True:
data = requests.get(someURL, self.port)
if data.loggedIn == True:
break
else:
pass
#Go onto logging in next user while we wait for the server to do things
listOfUsers = []
for i in range(3):
listOfUsers.append(user(3000+i)) # Creates 3 users
async def loginListOfUsers():
for user in users:
await user.login(user.port + "@gmail.com") # Logs in 3 users with i@gmail.com
loop = asyncio.get_event_loop()
loop.run_until_complete(loginListOfUsers())
I would like to know:
Is asyncio the right tool for what I am trying to do
How I would use asyncio to do it
Here is what I want/think asyncio can do:
Create an event loop,
Add coroutines to this loop and run them,
When it gets to a certain point e.g. an await statement it stops running that coroutine and moves on to the next one in the loop, pushing that one to the back of the loop
I don't have a great understanding of asyncio so am probaby very mistaken but hopefully you can understand what the problem I have is.