Python 的重试机制
为了避免由于一些网络或等其他不可控因素,而引起的功能性问题。比如在发送请求时,会因为网络不稳定,往往会有请求超时的问题。
这种情况下,我们通常会在代码中加入重试的代码。重试的代码本身不难实现,但如何写得优雅、易用,是我们要考虑的问题。
这里要给大家介绍的是一个第三方库-Tenacity(标题中的重试机制并并不准确,它不是Python的内置模块,因此并不能称之为机制),它实现了几乎我们可以使用到的所有重试场景,比如:
·在什么情况下才进行重试?
·重试几次呢?
·重试多久后结束?
·每次重试的间隔多长呢?
·重试失败后的回调?
在使用它之前,先要安装它
$pipinstalltenacity
1.最基本的重试
无条件重试,重试之间无间隔
fromtenacityimportretry
@retry
deftest_retry():
print("等待重试,重试无间隔执行...")
raiseException
test_retry()
无条件重试,但是在重试之前要等待2秒
fromtenacityimportretry,wait_fixed
@retry(wait=wait_fixed(2))
deftest_retry():
print("等待重试...")
raiseException
test_retry()
2.设置停止基本条件
只重试7次
fromtenacityimportretry,stop_after_attempt
@retry(stop=stop_after_attempt(7))
deftest_retry():
print("等待重试...")
raiseException
test_retry()
重试10秒后不再重试
fromtenacityimportretry,stop_after_delay
@retry(stop=stop_after_delay(10))
deftest_retry():
print("等待重试...")
raiseException
test_retry()
或者上面两个条件满足一个就结束重试
fromtenacityimportretry,stop_after_delay,stop_after_attempt
@retry(stop=(stop_after_delay(10)|stop_after_attempt(7)))
deftest_retry():
print("等待重试...")
raiseException
test_retry()
3.设置何时进行重试
在出现特定错误/异常(比如请求超时)的情况下,再进行重试
fromrequestsimportexceptions
fromtenacityimportretry,retry_if_exception_type
@retry(retry=retry_if_exception_type(exceptions.Timeout))
deftest_retry():
print("等待重试...")
raiseexceptions.Timeout
test_retry()
在满足自定义条件时,再进行重试。
如下示例,当test_retry函数返回值为False时,再进行重试
fromtenacityimportretry,stop_after_attempt,retry_if_result
defis_false(value):
returnvalueisFalse
@retry(stop=stop_after_attempt(3),
retry=retry_if_result(is_false))
deftest_retry():
returnFalse
test_retry()
4.重试后错误重新抛出
当出现异常后,tenacity会进行重试,若重试后还是失败,默认情况下,往上抛出的异常会变成RetryError,而不是最根本的原因。
因此可以加一个参数(reraise=True),使得当重试失败后,往外抛出的异常还是原来的那个。
fromtenacityimportretry,stop_after_attempt
@retry(stop=stop_after_attempt(7),reraise=True)
deftest_retry():
print("等待重试...")
raiseException
test_retry()
5.设置回调函数
当最后一次重试失败后,可以执行一个回调函数
fromtenacityimport*
defreturn_last_value(retry_state):
print("执行回调函数")
returnretry_state.outcome.result()#表示返回原函数的返回值
defis_false(value):
returnvalueisFalse
@retry(stop=stop_after_attempt(3),
retry_error_callback=return_last_value,
retry=retry_if_result(is_false))
deftest_retry():
print("等待重试中...")
returnFalse
print(test_retry())
输出如下
等待重试中...
等待重试中...
等待重试中...
执行回调函数
False
以上内容为大家介绍了Python的重试机制,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

相关推荐HOT
更多>>
Python元组怎么转换成列表
python中将元组转换成列表的方法是使用list()进行转换。使用示例:>>>T=(11,33,22,44)#元组对象>>>L=list(T)#转变为列表对象另外,可以使用tupl...详情>>
2023-11-06 20:15:08
python如何求次幂?
python中可以使用math模块中的pow()方法求次幂。pow()方法返回xy(x的y次方)的值。math模块pow()方法的语法:importmathmath.pow(x,y)示例:#!/u...详情>>
2023-11-06 18:27:10
python怎么import另一个python文件?
python使用import导入python文件的方法:示例:有a.py和b.py两个文件,当我们需要在b.py文件中应用a.py中的func()函数时,导入方法如下:同一文...详情>>
2023-11-06 17:47:37
python怎么判断文件夹下是否存在文件?
python判断文件夹下是否存在文件的方法:1、使用os.path.exists()方法判断文件是否存在importosos.path.exists(test_file.txt)#Trueos.pat详情>>
2023-11-06 14:20:14