1. 本际云推荐 - 专业推荐VPS、服务器,IDC点评首页
  2. 云主机运维
  3. VPS运维

Python重试机制是什么,下文给大家解答

介绍

小编写这篇文章的主要目的,主要是给大家讲解一下,关于Python机制的一些问题,比如重新调试的机制是什么呢?应用到它的场景还是很多的,下面跟小编一块去学习吧。

Python重试机制是什么,下文给大家解答

为了避免网络问题出现的错误,比如网络延迟或者是宕机,往往都会出现请求超时的问题。这里要给大家介绍的是一个第三方库-Tenacity(标题中的重试机制并并不准确,它不是Python的内置模块,因此并不能称之为机制),它实现了几乎我们可以使用到的所有重试场景,喜欢记得收藏、关注、点赞。

比如:

在什么情况下才进行重试?

重试几次呢?

重试多久后结束?

每次重试的间隔多长呢?

重试失败后的回调?

在使用它之前,先要安装它

 $pip install tenacity

重试示例

1.最基本的重试

无条件重试,重试之间无间隔

from tenacity import retry
 retry
def test_retry():
print("等待重试,重试无间隔执行...")
raise Exception
test_retry()

无条件重试,但是在重试之前要等待2秒

from tenacity import retry,wait_fixed
 retry(wait=wait_fixed(2))
def test_retry():
print("等待重试...")
raise Exception
test_retry()

2.设置停止基本条件

只重试7次

from tenacity import retry,stop_after_attempt
 retry(stop=stop_after_attempt(7))
def test_retry():
print("等待重试...")
raise Exception
test_retry()

重试10秒后不再重试

from tenacity import retry,stop_after_delay
 retry(stop=stop_after_delay(10))
def test_retry():
print("等待重试...")
raise Exception
test_retry()

或者上面两个条件满足一个就结束重试

from tenacity import retry,stop_after_delay,stop_after_attempt
 retry(stop=(stop_after_delay(10)|stop_after_attempt(7)))
def test_retry():
print("等待重试...")
raise Exception
test_retry()

3.设置何时进行重试

在出现特定错误/异常(比如请求超时)的情况下,再进行重试

from requests import exceptions
from tenacity import retry,retry_if_exception_type
 retry(retry=retry_if_exception_type(exceptions.Timeout))
def test_retry():
print("等待重试...")
raise exceptions.Timeout
test_retry()

在满足自定义条件时,再进行重试。如下示例,当test_retry函数返回值为False时,再进行重试

from tenacity import retry,stop_after_attempt,retry_if_result
def is_false(value):
return value is False
 retry(stop=stop_after_attempt(3),
retry=retry_if_result(is_false))
def test_retry():
return False
test_retry()

4.重试后错误重新抛出

当出现异常后,tenacity会进行重试,若重试后还是失败,默认情况下,往上抛出的异常会变成RetryError,而不是最根本的原因。因此可以加一个参数(reraise=True),使得当重试失败后,往外抛出的异常还是原来的那个。

from tenacity import retry,stop_after_attempt
 retry(stop=stop_after_attempt(7),reraise=True)
def test_retry():
print("等待重试...")
raise Exception
test_retry()

5.设置回调函数

当最后一次重试失败后,可以执行一个回调函数

from tenacity import*
def return_last_value(retry_state):
print("执行回调函数")
return retry_state.outcome.result()#表示返回原函数的返回值
def is_false(value):
return value is False
 retry(stop=stop_after_attempt(3),
retry_error_callback=return_last_value,
retry=retry_if_result(is_false))
def test_retry():
print("等待重试中...")
return False
print(test_retry())

输出如下

等待重试中...

等待重试中...

等待重试中...

执行回调函数

False

结论

至此,小编就为大家介绍到这里了,希望可以给各位读者带来帮助。

原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/7381.html