[英]Python: retry command after a API Request URL Failed
我有一些代碼來檢查 API 響應狀態,當它正確時,它將從 API 返回 reponse.json()。 但是,如果客戶端和服務器之間存在斷開連接並最終中斷 404 代碼,我想使用重試命令來擴展它,因為現在我只是重做相同的 function。
def API_status_report(url: str):
response = requests.get(url)
if response.status_code == 200:
return response.json()
elif response.status_code == 204:
return response.json()
elif response.status_code == 404:
print("Not Found: retrying")
API_status_report(url)
我目前正在查看重試模塊,但我仍然無法理解它,因為它有點令人困惑。 誰可以幫我這個事?
我們可能希望在這里避免遞歸API_status_report
調用(Python 支持遞歸,但沒有計划尾調用優化,無限遞歸深度可能會遇到麻煩)。
這是使用問題中建議的retry
模塊處理此問題的一種方法:
import requests
from retry import retry
class Exception404(Exception):
"""Custom error raised when a 404 response code is sent by the server."""
def __init__(self, message):
super().__init__(message)
@retry(Exception404, tries=3, delay=1)
def API_status_report(url: str):
response = requests.get(url)
if response.status_code == 200:
return response.json()
elif response.status_code == 204:
return response.json()
elif response.status_code == 404:
print("Not Found: retrying")
# Instead of recurring, we'll raise an Exception.
raise Exception404("Could not complete request")
if __name__ == "__main__":
# Good url: this should return successfully:
print(API_status_report("http://date.jsontest.com/"))
try:
# This is a bad url, but we'll try this three times.
print(API_status_report("http://jsontest.com/bad-data/"))
except Exception404:
# We can still handle the error to exit gracefully.
print("Handle the 404 Error.")
預期 output:
{'date': '04-18-2021', 'milliseconds_since_epoch': 1618766324441, 'time': '05:18:44 PM'}
Not Found: retrying
Not Found: retrying
Not Found: retrying
Handle the 404 Error.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.