zoukankan      html  css  js  c++  java
  • python自定义重试装饰器

     在生产环境中,某些环节因为IO的原因,可能会失败,为了解决这种代码逻辑上没有问题,但是只能通过多执行几次才能跑成功的问题,特地设计了这种重试模块.

    这个装饰器可以接收两个参数:最大重试次数和重试间隔

    import functools
    import time
    
    
    # 最大重试次数/重试间隔(单位秒)
    def retry(stop_max_attempt_number=10, wait_fixed=2):
        def decorator(func):
            @functools.wraps(func)
            def wrapper(*args, **kw):
                retry_num = 0
                while retry_num < stop_max_attempt_number:
                    rs = None
                    try:
                        rs = func(*args, **kw)
                        break
                    except Exception as e:
                        retry_num += 1
                        time.sleep(wait_fixed)
                        if retry_num == stop_max_attempt_number:
                            raise Exception(e)
                    finally:
                        if rs:
                            return rs
    
            return wrapper
    
        return decorator
  • 相关阅读:
    ajax全套
    url设计规范
    内置下划线方法
    rest_framework视图
    rest_framework
    数据库设置
    HDU 6231
    HDU 6242
    CodeForces 546D
    CodeForces 940E
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/13129748.html
Copyright © 2011-2022 走看看