亲宝软件园·资讯

展开

python 中的 retrying

autofelix  人气:0

一、安装

pip install retrying

二、一直请求

from retrying import retry

@retry()
def say():
try:
autofelix
except Exception as e:
# 可以将错误记录日志
print(e)
raise

say()

三、设置最大运行次数

from retrying import retry

@retry(stop_max_attempt_number=5)
def say():
try:
autofelix
except Exception as e:
# 可以将错误记录日志
print(e)
raise

say()

四、设置重试的最大时间

from retrying import retry

@retry(stop_max_delay=1000)
def say():
try:
autofelix
except Exception as e:
# 可以将错误记录日志
print(e)
raise

say()

五、设置间隔时间

from retrying import retry

@retry(wait_fixed=1000)
def say():
try:
autofelix
except Exception as e:
# 可以将错误记录日志
print(e)
raise

say()

六、设置随机间隔时间

from retrying import retry

@retry(wait_random_min=5000, wait_random_max=50000)
def say():
try:
autofelix
except Exception as e:
# 可以将错误记录日志
print(e)
raise

say()

七、随机倍数间隔时间

from retrying import retry

@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000)
def say():
try:
autofelix
except Exception as e:
# 可以将错误记录日志
print(e)
raise

say()

八、指定异常类型

from retrying import retry

def retry_error(exception):
return isinstance(exception, RetryError)

# 会重复调用
@retry(etry_on_exception=retry_error)
def say():
try:
autofelix
except RetryError as e:
raise RetryError

# 只调用一次
@retry(etry_on_exception=retry_error, wrap_exception=True)
def say():
raise Exception('a')

say()

九、过滤回调

from retrying import retry

def retry_filter(result):
print("this is result")
return result is not None

@retry(retry_on_result=retry_filter)
def say():
print('Retry forever ignoring Exceptions with no wait if return value is None')
return None

say()

十、异常执行

from retrying import retry

def stop_record(attempts, delay):
print("logging %d--->%d" % (attempts,delay))

@retry(stop_max_delay=10, stop_func=stop_record)
def say():
print("i am autofelix")
raise Exception

say()

加载全部内容

相关教程
猜你喜欢
用户评论