美文网首页
python 重试策略

python 重试策略

作者: 灰化肥发黑会挥发 | 来源:发表于2020-11-02 17:23 被阅读0次

    python 有一个非常有意思包retrying,可以用来自动化的进行重试操作,支持的条件也比较多,基本上能满足我的日常需求。
    在没有用retrying之前,我的代码结构是这样的:

        try_times = 2
        response = None
        while True:
            try:
                 response = request.post(URL)
            except Exception as e:
                if try_times > 0:
                    time.sleep(3)
                    try_times -= 1
                else:
                        logger.info(response.json())
                        if response.json()['errno'] == 1000:
                            raise TimeoutError
                    raise Exception("failed")
    

    代码可以说是非常的不优雅。retrying支持使用装饰器来对函数单元进行处理。改造后为

        from retrying import retry
        def retry_TimeoutError(exception):
            return isinstance(exception, TimeoutError)
    
        @retry(stop_max_attempt_number=3,
               wait_fixed=3000,
               retry_on_exception=retry_TimeoutError)
        def retry_request_translate(self, content, input_len):
            try:
                response = requests.post(url, json=payload)
                return result
            except Exception as e:
                if response is not None:
                    if response.json()['errno'] == 1000:
                        raise TimeoutError
                raise Exception("failed")
    

    retry的参数支持:

    • stop_max_attempt_number: 最大重试次数;
    • wait_fixed: 重试之间的间隔时间,单位为毫秒;
    • retry_on_exception: 捕获特定异常才重试,例如我这里自己申明了超时的判断;
    • 其它:


      image.png

    相关文章

      网友评论

          本文标题:python 重试策略

          本文链接:https://www.haomeiwen.com/subject/juvmvktx.html