Python中的重试机制

发布时间 2023-03-23 12:39:15作者: pu369com

====引用自https://www.jb51.net/article/254886.htm(一文详解Python中的重试机制)

这里要给大家介绍的是一个第三方库 - Tenacity (标题中的重试机制并并不准确,它不是 Python 的内置模块,因此并不能称之为机制),它实现了几乎我们可以使用到的所有重试场景

=====

示例:

from tenacity import *
from requests import exceptions
 
def return_last_value(retry_state):
    print("执行回调函数")
    return "原函数的返回值:"+ str(retry_state.outcome.result())  # 表示返回原函数的返回值
 
def is_false(value):
    return value is False
 
@retry(wait=wait_fixed(2),stop=stop_after_attempt(3),
       retry_error_callback=return_last_value,
       retry=(retry_if_result(is_false) | retry_if_exception_type(exceptions.Timeout)),
       reraise=True)
def test_retry():
    print("等待重试中...")
    return False
 
print(test_retry())

  

 

 

 

 

参考:https://www.jb51.net/article/254886.htm