[英]Python HTTPS Request : Retry on Status Code return on API
我嘗試使用Python 3.6對某些HTTP狀態和網絡錯誤進行重試,也針對對外部API的請求進行重試。
我目前已按照不同的准則實施了此代碼:
我的代碼(僅重要部分)除代碼外,我未在此處顯示所有嘗試
import requests
import logging
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from urllib3.exceptions import MaxRetryError
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s :%(levelname)s : %(funcName)s - %(message)s')
def make_api_request(url):
try:
s = requests.Session()
retries = Retry(total=6, backoff_factor=1, connect=5, status=3, status_forcelist=[400, 401, 404, 500, 501, 502])
# Prepare the request with Retry
s.mount("https://", HTTPAdapter(max_retries=retries))
s = requests.get(url, proxies=def_proxies)
# Status Code checking
if s.status_code != 200:
logging.error("Warning : Status Code call <> 200: {}".format(s.status_code))
return s.json()
# Request Exception Handling
except MaxRetryError as maxer:
print("Max Retries Error:", maxer)
except requests.exceptions.HTTPError as errh:
print("Http Error:", errh)
except requests.exceptions.ConnectionError as errc:
print("Error Connecting:", errc)
except requests.exceptions.Timeout as errt:
print("Timeout Error:", errt)
except requests.exceptions.RequestException as err:
print("OOps: Something Else", err)
在“我的日志”中,沒有任何內容表明我已經執行了重試,因此我添加了一個MaxRetryError來捕獲它,但是沒有引發任何問題
所以我決定啟動Wireshark :-(
我在帶有錯誤登錄名的401上進行模擬時看到的內容
12 2.917294 192.168.43.85 69.84.209.64 TCP 66 61620 → 443 [SYN] Seq=0 Win=17520 Len=0 MSS=1460 WS=256 SACK_PERM=1
14 2.972088 192.168.43.85 69.84.209.64 TCP 54 61620 → 443 [ACK] Seq=1 Ack=1 Win=17408 Len=0
15 3.168677 192.168.43.85 69.84.209.64 TLSv1.2 571 Client Hello
20 3.314637 192.168.43.85 69.84.209.64 TCP 66 61620 → 443 [ACK] Seq=518 Ack=1337 Win=16128 Len=0 SLE=2673 SRE=4009
22 3.315087 192.168.43.85 69.84.209.64 TCP 54 61620 → 443 [ACK] Seq=518 Ack=4009 Win=17408 Len=0
26 3.316322 192.168.43.85 69.84.209.64 TCP 54 61620 → 443 [ACK] Seq=518 Ack=5619 Win=17408 Len=0
27 3.318149 192.168.43.85 69.84.209.64 TLSv1.2 412 Client Key Exchange, Change Cipher Spec, Encrypted Handshake Message
35 3.475570 192.168.43.85 69.84.209.64 TLSv1.2 363 Application Data
38 3.674813 192.168.43.85 69.84.209.64 TCP 54 61620 → 443 [ACK] Seq=1185 Ack=6179 Win=16896 Len=0
40 3.874986 192.168.43.85 69.84.209.64 TCP 54 61620 → 443 [FIN, ACK] Seq=1185 Ack=6248 Win=16640 Len=0
43 4.034423 192.168.43.85 69.84.209.64 TCP 54 61620 → 443 [ACK] Seq=1186 Ack=6249 Win=16640 Len=0
完全沒有重試的證據
冒犯我的錯誤,我要做的就是
res = s.get(url, proxies=def_proxies)
if res.status_code != 200:
logging.error("Warning : Status Code call <> 200: {}".format(res.status_code))
else:
return res.json()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.