I work at a webproject were I need to 1) create a user 2) log in with the user credentials. The problem is there's an unspecified amount of time before the user gets added to the database, so I need to wait for that amount of time.
I want to create an explicit wait that would send GET requests every n seconds until the response contains the added user credentials.
from time import sleep
from requests import Session
session = Session()
url = 'app_url_with_user_list_endpoint'
resp = session.get(url=url)
while resp.json()[-1]["email"] != "[email protected]":
sleep(0.5)
resp = session.get(url=url)
Here, I tried to update the resp until it contains the new user email. But, I just created an infitine loop.
So, how do I wait for the response to hold the desired email? Optional: how do I specify max number of retries?
CodePudding user response:
Does the following work? (Limited to 10 tries, which here amounts to a timeout of 5 seconds.)
from time import sleep
from requests import Session
session = Session()
url = 'app_url_with_user_list_endpoint'
match = "[email protected]"
success = False
for _ in range(10):
resp = session.get(url=url)
if resp.json()[-1]["email"] == match:
success = True
break
sleep(0.5)
if success:
print("Success: User was added")
else:
print("Timeout: Failed to add user")