01.安装
pip install tenacity
02.使用
(1)使用规则
-
同一个参数,多个值用 |(或),+(与)进行组合使用
-
不同参数之间,只有组合使用,通过关键字参数传参即可
(2)@retry()【常用】
- 【无条件重试】,只要抛出异常就会重试,直到执行不抛异常
from tenacity import *
一直重试
@retry()
def test_demo():
print('执行 test_demo')
raise Exception('手动抛出异常')
test_demo()
一直执行 test_demo 函数
(3)@retry(stop=stop_after_attempt(3))【常用】
- 指定【重试的次数】,如 3 次
from tenacity import *
重试 3 次后停止
@retry(stop=stop_after_attempt(3))
def test_demo():
print('执行 test_demo')
raise Exception('手动抛出异常')
test_demo()
执行三次 test_demo 函数
(4)@retry(stop=stop_after_delay(5))【常用】
- 指定【重试多长时候后停止】,如 5 秒
from tenacity import *
重试 5 秒后停止
@retry(stop=stop_after_delay(5))
def test_demo():
print('执行 test_demo')
raise Exception('手动抛出异常')
test_demo()
(5)@retry(stop=(stop_after_delay(1) | stop_after_attempt(5)))
- stop_after_delay()和 stop_after_attempt()组合使用,只要其中一个条件满足,任务就停止
from tenacity import *
重试 2 秒或者重试 50 次停止
@retry(stop=(stop_after_delay(2) | stop_after_attempt(50)))
def test_demo():
print('执行 test_demo')
raise Exception('手动抛出异常')
test_demo()
(6)@retry(wait=wait_fixed(3))【常用】
- 指定每一次【重试时等待时间】,如 3 秒,每一次重试前都要等待 3 秒钟
from tenacity import *
每次重试的等待时间 5 秒
@retry(wait=wait_fixed(5))
def test_demo():
print('执行 test_demo')
raise Exception('手动抛出异常')
test_demo()
(7)@retry(wait=wait_random(min=1, max=5))
- 【重试时等待时间】在 min,max 之间随机取值
from tenacity import *
重试间隔时间 1-5 秒随机
@retry(wait=wait_random(min=1, max=5))
def test_demo():
print('执行 test_demo')
raise Exception('手动抛出异常')
test_demo()
(8)@retry(wait=wait_fixed(3) + wait_random(0, 2))
-
wait_fixed(3) 与 wait_random(0, 2)组合使用,两个条件都满足
-
比如每次等待 3 秒
from tenacity import *
随机等待 0-2 秒和每次等待 3 秒重试都满足才会重试
@retry(wait=wait_fixed(3) + wait_random(0, 2))
def test_demo():
print('执行 test_demo')
raise Exception('手动抛出异常')
test_demo()
(9)@retry(retry=retry_if_exception_type(IOError))
- 指定特定类型的异常出现时,任务才重试,会一直重试
from tenacity import *
指定 TypeError 才会重复
@retry(retry=retry_if_exception_type(TypeError))
def test_demo():
print('执行 test_demo')
print('a'+1)
test_demo()
(10)组合使用
@retry(wait=wait_random(min=1, max=5),stop=stop_after_attempt(3))
def test_demo():
print('执行 test_demo')
raise Exception('手动抛出异常')
test_demo()
最后我也给大家准备了400页软件测试核心知识点,这份知识点已经帮助许多人走过了那些学习最艰难的时刻,希望也能帮助到你们,有需要的小伙伴可以关注我的微信公众号:程序员二黑,自提!
也欢迎加入我的软件测试交流群:785128166,大家一起学习,有人陪伴,不会孤单!
如果文章对你有帮助的话,就帮我点个三连吧!