
您可以使用自定义的适配器,并对所有 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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号