IdeoREX IdeoREX - 7 days ago 4
HTTP Question

Retry <Response [404]> until I get <Response [200]>

I'm building a web app that calls API. The API I'm currently using currently (it fluctuates) has a respawn time (probable not the correct term) of 210 seconds.

The API call in requests is:

r = requests.post(url ,headers=headers, auth=auth, data=json.dumps(data))


After the call
r
can equal
<Response [404]>
or
<Response [200]>
. I want to run this API call until it returns a
<Response [200]>
. What format is
<Response [200]>
in?

My current loop is as follows. Is there a better way to do this?

while True:
r = requests.post(url ,headers=headers, auth=auth, data=json.dumps(data))
if (r == '<Response [200]>'): break

Answer

You are confusing the repr() output with the object.

Response objects have a .status_code attribute, test against that:

if r.status_code == 200:
    break

However, to hammer a service repeatedly until it gives you a 200 response is likely to get your IP address blocked. Build in some kind of exponential back-off to prevent DOS-ing the API.