如何获取requests库Retry模块成功前的重试失败次数?
requests Retry模块失败尝试次数说明
你的配置中,total=3代表最多会进行3次失败重试,加上最开始的1次初始请求,总共会有4次请求尝试。也就是说,在成功请求之前,最多会经历3次失败尝试。
参数细节解释
total=3:这个值是重试的总次数,初始请求并不计入这个数值。只有当请求触发了重试条件(返回status_forcelist中的状态码、且是allowed_methods指定的GET方法)时,才会开始计数重试。status_forcelist:列出了需要触发重试的HTTP状态码,比如429(请求超限)、5xx系列服务器错误等。backoff_factor=1:重试间隔会按照backoff_factor * (2 ** (重试次数-1))的规则递增,比如第一次重试等待1秒,第二次2秒,第三次4秒。
代码里的问题修正
你的异常捕获写法有误,except MaxRetryError and RetryError: 无法正确同时捕获这两个异常,正确的写法应该用逗号分隔多个异常类型:
try: response = http.get(url) except (MaxRetryError, RetryError): print("Still no success after 4 attempts - skipping")
如何统计实际重试次数
如果想要知道本次请求实际发生了多少次失败重试,可以给Retry添加raise_on_status=False参数(允许返回错误状态码而不直接抛出异常),然后通过response.raw.retries获取重试统计:
from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry from urllib3.exceptions import MaxRetryError from requests.exceptions import RetryError import requests # 补充代码中缺失的导入 url = "https://api.github.com/user/repos?page=1" retry_strategy = Retry( total=3, status_forcelist=[429, 401, 500, 502, 503, 504], allowed_methods=["GET"], backoff_factor=1, raise_on_status=False ) adapter = HTTPAdapter(max_retries=retry_strategy) http = requests.Session() http.mount("https://", adapter) http.mount("http://", adapter) try: response = http.get(url) # 打印实际重试次数 print(f"实际重试次数: {response.raw.retries.total}") # 如果最终还是失败状态,再做处理 if response.status_code in retry_strategy.status_forcelist: print("请求最终仍失败") except (MaxRetryError, RetryError): print("Still no success after 4 attempts - skipping")
内容的提问来源于stack exchange,提问作者Shriniwas
相关产品推荐
相关产品推荐

