直到“requests”库支持指数退避的自动重试
您可以使用自定义的适配器,并对所有 http/https 请求强制执行指数退避因子多次重试。请参阅下面的示例:
import requestsfrom requests import adaptersfrom urllib3.util import retry# create a transport adapter with a custom retry strategy.retries = retry( total=3, backoff_factor=3, status_forcelist=[500, 502, 503, 504])adapter = adapters.httpadapter(max_retries=retries)# ensure adapter is used for both http and https requests.session = requests.session()session.mount('https://', adapter)session.mount('http://', adapter)# testing the retry mechanismresponse = session.get("http://httpbin.org/status/500")
这将返回以下错误:
RetryError: HTTPConnectionPool(host='httpbin.org', port=80): Max retries exceeded with url: /status/500 (Caused by ResponseError('too many 500 error responses'))
不幸的是,似乎没有办法知道上述机制尝试了多少次重试,只有当所有尝试都已用尽时
参考
https://stackoverflow.com/a/47475019/4477547