python中的重试

安装: pip install retrying
https://blog.csdn.net/liereli/article/details/79993114
@retry 装饰器会对函数不断的重试

#默认无限重试
@retry()
def pick_one():
    print('pick')
    t = random.randint(0, 2)
    print(t)
    if t != 1:
        raise Exception('1 is not picked')
        
if __name__ == '__main__':
    '''
    '''
    pick_one()	#随机数不等于1则一直重试,等于1则停止
1、retry(wait_fixed = 1000)	#设置重试间隔时长(ms  1000ms = 1s)
2、retry(wait_random_min = 1000,wait_random_max = 2000,)	#随机重试间隔,将在1~2s内
3、retry(stop_max_attempt_number = 3)		#最大重试次数,超过后正常抛出异常
4、retry(stop_max_delay = 2000)			#最大延迟时长,2s内未满足条件则抛出异常
5、retry(wait_exponential_multiplier = ,wait_exponential_max = )	#以指数的形式产生两次retrying之间的停留时间。wait_exponential_multiplier和wait_exponential_max:以指数的形式产生两次retrying之间的停留时间,产生的值为2^previous_attempt_number * wait_exponential_multiplier),
previous_attempt_number是前面已经retry的次数,如果
产生的这个值超过了wait_exponential_max的大小,那么之后两个retrying之间的停留值都为wait_exponential_max。这个设计迎合
了exponential backoff算法,可以减轻阻塞的情况
6、retry(retry_on_exception = 函数)		#当发生指定异常时才会重试
#--------------
def my_exc2(exc):
    return isinstance(exc,ZeroDivisionError)

@retry(retry_on_exception = my_exc2)
def pick_one():
    # sleep(2)
    print('pick')
    t = random.randint(0, 2)
    print(t)
    if t != 1:
        a = 1/0

if __name__ == '__main__':
    '''
    '''
    pick_one()	#当发生ZeroDivisionError时才会重试,其他异常不会重试

7、retry(retry_on_result = 函数)		#对结果的判定   将被修饰函数的返回值传人函数,如果函数返回true则重试
#--------------
def my_res(result):
    print(result)
    return isinstance(result,str)
@retry(retry_on_result = my_res)
def pick_one():
    print('pick')
    t = random.randint(0, 2)
    print(t)
    if t != 1:
        return '100'
if __name__ == '__main__':
    '''
    '''
    pick_one()		#t != 1 时pick_one返回‘100’,my_res返回True 则重试

8、retry(stop_func = 函数) #每次抛出异常时都会执行的函数,如果和stop_max_delay、stop_max_attempt_number配合使用,则后两者会失效,指定的stop_func会有两个参数:attempts, delay
#--------------
def stop_fun(attempts, delay):
    print("stop_func %d--->%d" % (attempts,delay))
@retry(stop_func = stop_fun)
def pick_one():
    t = random.randint(0, 2)
    if t != 1 or t == 1:
        a = 1/0
        raise Exception(FileNotFoundError('1 is not picked'))
        
if __name__ == '__main__':
    '''
    '''
    pick_one()
    wait_fixed = None




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值