![](/img/trans.png)
[英]Python requests.post() method command returns 200 status_code attribute instead of 500
[英]retry with python requests when status_code = 200
我向其發送請求的 API 的響應格式有點不尋常
它總是返回status_code = 200
返回的 json 中有一個額外的error
鍵,詳細說明了響應的實際狀態:
2.1. error = 0
表示成功完成
2.2. error != 0
表示出現問題
我正在嘗試在urlib3
使用 Retry 類,但到目前為止我知道它只使用響應中的status_code
,而不是它的實際內容。
還有其他選擇嗎?
我認為您將不得不在這里使用“混合”方法,並在分析后手動重試。
如果我status_code
錯的話,即使您的請求不好,API 也總是返回status_code
200。 所以我們需要處理兩種情況,並編寫我們自己的重試處理程序。 您可以嘗試類似這種方法,該方法還會考慮您發出的請求數量,以確定是否存在重復錯誤情況。
import requests
import time
import json
r = None
j = None
attempts = 0
while (attempts < 5):
# Make request, make sure you have the right data= for payload or json= for
# JSON payloads in your request. And repolace `get` with the proper method
# such as POST or PUT if it's not a GET.
attempts += 1
r = requests.get('http://api.example.com/', data=...)
if r.status_code != 200:
time.sleep(5) # Wait between requests for 5 seconds
continue # Go back to the beginning of the loop
else:
# Decode the bytes in the reply content, then parse it as JSON.
j = json.loads(r.content.decode('UTF-8'))
# Check what the output of the 'error' key in the JSON is
if j['error'] != 0:
# If there's an error code, then restart the loop and request
# after a 5 second pause again.
time.sleep(5)
continue
else:
# If there is no error, simply break the loop, and go on to
# processing code after it.
break
if attempts >= 5:
raise RuntimeError("Consistently invalid or error case returned from API.")
# If there's no error then...
# Do something with the output of `j` which is now a dict containing the parsed
# JSON data.
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.