- 问题背景
最近在Python开发中遇到一个问题,某个API接口由于一些问题会存在偶尔返回503的错误,所以需要在请求中增加失败重试机制。 - 解决办法
- 在参考“详解超时和重试”中的解决方法时,发现重试机制没有生效!!在阅读源码后发现:
也就是说只有在max_retries: The maximum number of retries each connection should attempt. Note, this applies only to failed DNS lookups, socket connections and connection timeouts, never to requests where data has made it to the server. By default, Requests does not retry failed connections. If you need granular control over the conditions under which we retry a request, import urllib3's ``Retry`` class and pass that instead.
failed DNS lookups, socket connections and connection timeouts
这几种情况下才会重试,而我当前的问题是503错误,所以不会重试。 - 继续寻找后在stack overflow发现了一篇帖子“Can I set max_retries for requests.request?”
,其中提到了几中常用的重试机制,我尝试用@backoff
装饰器的方式解决遇到的问题,在这个装饰器中可以配置重试的条件、退避的方式backoff.fibo(斐波那契),backoff.expo(指数)...
、重试放弃的条件等等十分有效的参数。
在配置异常类型为requests.exceptions.RequestException
后,发现HTTPError
依然无法引起重试,在参考了Correct way to try/except using Python requests module?
和python-requests快速上手后发现此类异常需要使用raise_for_status
方法才能抛出,后续又在backoff.on_exception中添加了giveup
和on_giveup
两个参数实现了错误码为4XX时放弃和错误信息的记录。
- 在参考“详解超时和重试”中的解决方法时,发现重试机制没有生效!!在阅读源码后发现:
Python requests失败重试机制
猜你喜欢
转载自blog.csdn.net/shengruxiahua2571/article/details/103165315
今日推荐
周排行