Python requests失败重试机制

  1. 问题背景
    最近在Python开发中遇到一个问题,某个API接口由于一些问题会存在偶尔返回503的错误,所以需要在请求中增加失败重试机制。
  2. 解决办法
    • 在参考“详解超时和重试”中的解决方法时,发现重试机制没有生效!!在阅读源码后发现:
       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中添加了giveupon_giveup两个参数实现了错误码为4XX时放弃和错误信息的记录。

参考
backoff详解
backoff 1.10.0

发布了16 篇原创文章 · 获赞 0 · 访问量 806

猜你喜欢

转载自blog.csdn.net/shengruxiahua2571/article/details/103165315
今日推荐