登录
首页 >  文章 >  python教程

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

来源:dev.to

时间:2024-12-06 21:21:45 371浏览 收藏

golang学习网今天将给大家带来《直到“requests”库支持指数退避的自动重试》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习文章或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

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

您可以使用自定义的适配器,并对所有 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

今天带大家了解了的相关知识,希望对你有所帮助;关于文章的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>