I need to use API that performs a task in two steps:
- POST request: to submit a task and get back the results URL
- GET request: to check for a status of the results URL and get the result when the status is "completed"
Below I provide my implementation. However, I don't know how to perform the waiting
while GET
returns the completion status equal to 0.
import requests
url = "https://xxx"
headers = {"Content-Type": "application/json", "Ocp-Apim-Subscription-Key": "xxx"}
body = {...}
response = requests.post(url, headers=headers, json=body)
status_code = response.status_code
url_result = response.headers['url-result']
# Step 2
s2_result = requests.get(url_result, headers=headers)
s2_result = s2_result.json()
s2_result_status = s2_result['completed']
if s2_result_status == 1:
# ...
else:
# wait 1 second and repeat
CodePudding user response:
You need to repeat the get
in a loop. I suggest you use Session()
to prvent connection errors
with requests.Session() as s:
c = 0
while c < 10: # add a limit
s2_result = s.get(url_result, headers=headers)
s2_result = s2_result.json()
s2_result_status = s2_result['completed']
if s2_result_status == 1:
break
else:
time.sleep(1)
CodePudding user response:
The idea of waiting for 1 second and repeating can definitely solve your problem. You can use time.sleep(1)
. For example,
# Step 2
while True:
s2_result = requests.get(url_result, headers=headers)
s2_result = s2_result.json()
s2_result_status = s2_result['completed']
if s2_result_status == 1:
# ...
break
else:
# wait 1 second and repeat
time.sleep(1)
Reminders: Do not forget to check the http status code of response before you call s2_result.json()
. And, using s2_result.get('completed')
rather than s2_result['completed']
makes your program more robust.