46重试装饰器retry

 

复制代码
from retrying import retry

r'''
安装:pip install retrying
Version: 1.3.4
作用:retrying库是Python中用于实现重试机制的库,它们的目的都是在遇到错误或异常时自动重试代码块,以增加代码的健壮性和可靠性.
下面的案例抽几个常用参数说明retry装饰器,当然也可以自己编写代码实现重试。
'''

# 只要是出现异常就会重试(无限重试),这里设置了为10次
num = 1


@retry
def do_something():
    global num
    if num < 10:
        num += 1
        print('Retry')
        raise Exception("Retry")


# stop_max_attempt_number: 用来设定最大的尝试次数,超过该次数就会停止,并抛出最后一次的异常
@retry(stop_max_attempt_number=7)
def do_run():
    print('Retry')
    raise Exception("Retry")


# wait_fixed: 设置在两次retrying之间的停留时间,这里设置为1s,无限重试
@retry(wait_fixed=1000)
def do_time():
    print('Retry')
    raise IOError("Retry")


# 重试功能的简单实现,count 控制重试次数,tag控制是否重试。
def reachFun():
    count = 0
    tag = False
    while count < 10 and tag is False:
        print('Retry')
        count += 1
        if count == 10:
            tag = True


if __name__ == '__main__':
    # do_something()
    # do_run()
    # do_time()
    reachFun()
复制代码

 

posted @   冷夜O  阅读(49)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示