一、装置
循环、反复回调咱们在很多场景中会用到
不仅在领取场景中,咱们须要通过重复的回调晓得用户的领取状态
还有在申请中,如果申请失败,咱们须要再从新进行进行申请,避免申请异样导致数据缺失

pip install retrying

二、始终申请
如果咱们心愿在代码碰到异样时,始终回调,直到胜利
上面办法中,咱们间接拜访一个未定义的变量,必定会走上面的Exception中
这个时候咱们能够将这一次谬误写进日志,然而让程序继续执行这个办法,直到没有异样为止
因为这里模仿的是必定有异样,所以该程序会始终返回回调,不间断的周而复始

from retrying import retry@retry()def say():  try:    autofelix  except Exception as e:    # 能够将谬误记录日志    print(e)    raise    say()

三、设置最大运行次数
如果咱们在申请中遇到异样时候
能够通过 stop_max_attempt_number 设置一个最大运行次数
当回调次数超过设置值,将不再执行回调
这里咱们设置最大运行次数为5次

from retrying import retry@retry(stop_max_attempt_number=5)def say():  try:    autofelix  except Exception as e:    # 能够将谬误记录日志    print(e)    raise    say()

四、设置重试的最大工夫
能够通过 stop_max_delay 设置失败重试的最大工夫, 单位毫秒
超出工夫,则进行重试

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()

七、随机倍数间隔时间
能够通过设置 wait_exponential_multiplier 间隔时间倍数减少
能够通过设置 wait_exponential_max 最大间隔时间

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()

八、指定异样类型
能够通过 retry_on_exception 设置指定异样类型
指定的异样类型会重试,不指定的类型,会间接异样退出
如果设置 wrap_exception 参数为True,则其余类型异样

from retrying import retrydef 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()

九、过滤回调
能够设置 retry_on_result 指定哪些后果须要去回调
将申请后果放到 retry_on_result 指定办法中进行过滤,如果返回None,则持续回调,否则就完结

from retrying import retrydef 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()

十、异样执行
通过设置 stop_func 每次抛出异样时都会执行的函数
如果和stop_max_delay、stop_max_attempt_number配合应用,则后两者会生效

from retrying import retrydef 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 Exceptionsay()

以上就是本次分享的全部内容,当初想要学习编程的小伙伴欢送关注Python技术大本营,获取更多技能与教程。