Noonisy
Do U Know(2023-04-25)
2023-04-25
阅读:308

DO U KNOW?


1.tenacity库

函数异常进行重试
pip insatll tenacity

无限重试

from tenacity import retry

@retry
def func():
    print('Retry forever')
    raise Exception

设置停止条件

from tenacity import retry, stop_after_attempt, stop_after_delay

# 重试 5次后停止
@retry(stop=stop_after_attempt(5)):
def func():
    print('Stop after 5 times')
    raise Exception

# 开始 5s 后停止
@retry(stop=stop_after_delay(5)):  
def func():
    print('Stop after 5s')
    raise Exception

# 使用|进行组合,满足一个即停止
@retry(stop=(stop_after_attempt(5) | stop_after_attempt(5))):
def func():
    print('Stop after 5 times or 5s')
    raise Exception

重试之前等待

from tenacity import retry, wait_fixed, wait_random, stop_after_attempt, wait_exponential, wait_random_exponential

# 等待固定 2s
@retry(wait=wait_fixed(2), stop=stop_after_attempt(5)) 
def func():
    print('Wait 2s before next retry')
    raise Exception

# 等待随机 1s 或 2s
@retry(wait=wait_random(min=1, max=2), stop=stop_after_attempt(5))
def func():
    print('Wait 1s or 2s')
    raise Exception

# 等待 3^x 秒, 最多30秒
@retry(wait=wait_exponential(multiplier=3, max=30), stop=stop_after_attempt(10))
def func():
    print('Wait')
    raise Exception

# 随机等待 [3^x, 30] 秒, 最多等待 30s
@retry(wait=wait_random_exponential(multiplier=3, max=30), stop=stop_after_attempt(10))
def func():
    print('Wait')
    raise Exception

特定异常才重试

from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_random

@retry(retry=retry_if_exception_type(ValueError), stop=stop_after_attempt(10), wait=wait_random(1, 5))
def func():
    print('Retry')
    raise ValueError

自定义异常

References

最后编辑于:2024 年 03 月 28 日 06:28
邮箱格式错误
网址请用http://或https://开头