python_重试模块

参考网址:http://www.nnzhp.cn/archives/812

安装第3方模块 pip3 install retrying

import requests
from retrying import retry

count=0
@retry(stop_max_attempt_number=4)#重试次数4
def test():
    global count
    print('run')
    if count!=5:
        count=1
        raise  Exception('出错了') #重试4次后,仍不成功,给予提示,如果在规定的重试次数内重试成功,就不在提示

test() #调取函数

@retry(stop_max_attempt_number=3,stop_max_delay=1000)
#stop_max_attempt_number最大重试次数, 3次, stop_max_delay是3次重试间隔多少毫秒,间隔1秒
def test2():
    r=requests.get('http://localhost:8080/chapter02/welcome.html ',{'xx':'xx'})
    if '请稍后重试' in r.text:
        # 自己判断什么时候重试,比如说服务端返回某个信息,就主动抛出一个异常,这样它就会自动重试
        raise Exception('服务端现在有点问题')
test2()
原文地址:https://www.cnblogs.com/xiaokuangnvhai/p/11281650.html