How to wait for a specific http response in python

11,925

Be aware that if the value of the response changes while checking in the while condition it will also stop the iteration, so the if statement inside the while is not needed.

Note: the response object has to be able to change its value otherwise it will always be the same as it is a just a variable and not a function that checks a response

You can add a simple if statement with a time value

def waitForResourceAvailable(response, time):
    timer = 0
    while response.status_code == 204:
        time.sleep(10)
        timer += 10
        if timer > time:
            break
        if response.status_code == 200:
            break

Making it even better would be like:

def waitForResourceAvailable(response, timeout, timewait):
    timer = 0
    while response.status_code == 204:
        time.sleep(timewait)
        timer += timewait
        if timer > timeout:
            break
        if response.status_code == 200:
            break
Share:
11,925
Aurelio
Author by

Aurelio

Updated on December 09, 2022

Comments

  • Aurelio
    Aurelio over 1 year

    I have a problem waiting for a response 200. When I perform my get request the expected resource isn't there and the response is 204. What I want to do is wait for two minutes and lets say call every 10 seconds to check is the response is 200. If time is out, I want to return an error.

    def waitForResourceAvailable(response):
        while response.status_code == 204:
            time.sleep(10)
            if response.status_code == 200:
                break
    

    This works well, but I need a solution to exit the loop in case of status code 200 not to appear in a specified time.

    • Alex Yu
      Alex Yu about 5 years
      HTTP code 204 or 404 or even 50x - are absolutely normal response codes. Why do you expect 200 exactly? Are you responsible for server application? Which url are you trying?
    • chepner
      chepner about 5 years
      response is fixed; neither it nor any part of it is going to change in the code you show. You have to repeat the request if you want a different response.
    • Aurelio
      Aurelio about 5 years
      I run a command via REST-API and this command generates a report. When starting the command the response contains the reportID, but the report is not generated yet. So my next command to fetch the report has to wait until the resource is available.