函数异常
进行重试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