首页 > 后端开发 > Python教程 > 直到'requests”库支持指数退避的自动重试

直到'requests”库支持指数退避的自动重试

Barbara Streisand
发布: 2024-12-27 15:00:15
原创
355 人浏览过

TIL that the `requests` library supports automatic retries with exponential backoff

您可以使用自定义适配器,并对所有 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中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板