您可以使用自定义适配器,并对所有 HTTP/HTTPS 请求强制以指数退避因子进行多次重试。请参阅下面的示例:
import requests from requests import adapters from 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 mechanism response = 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
以上是直到'requests”库支持指数退避的自动重试的详细内容。更多信息请关注PHP中文网其他相关文章!