Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to resend GET request with requests library until I get desired response? (Python)

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"] != "new_use@samplemail.fake":
     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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, how do I wait for the response to hold the desired email? Optional: how do I specify max number of retries?

>Solution :

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 = "new_use@samplemail.fake"

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading