python|python 重试策略
python
有一个非常有意思包retrying
,可以用来自动化的进行重试操作,支持的条件也比较多,基本上能满足我的日常需求。
在没有用retrying
之前,我的代码结构是这样的:
try_times = 2
response = None
while True:
try:
response = request.post(URL)
except Exception as e:
if try_times > 0:
time.sleep(3)
try_times -= 1
else:
logger.info(response.json())
if response.json()['errno'] == 1000:
raise TimeoutError
raise Exception("failed")
代码可以说是非常的不优雅。
retrying
支持使用装饰器来对函数单元进行处理。改造后为from retrying import retry
def retry_TimeoutError(exception):
return isinstance(exception, TimeoutError)@retry(stop_max_attempt_number=3,
wait_fixed=3000,
retry_on_exception=retry_TimeoutError)
def retry_request_translate(self, content, input_len):
try:
response = requests.post(url, json=payload)
return result
except Exception as e:
if response is not None:
if response.json()['errno'] == 1000:
raise TimeoutError
raise Exception("failed")
retry
的参数支持:-
stop_max_attempt_number:
最大重试次数; -
wait_fixed:
重试之间的间隔时间,单位为毫秒; -
retry_on_exception:
捕获特定异常才重试,例如我这里自己申明了超时的判断; - 【python|python 重试策略】其它:
文章图片
image.png
推荐阅读
- python学习之|python学习之 实现QQ自动发送消息
- 逻辑回归的理解与python示例
- python自定义封装带颜色的logging模块
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- Python基础|Python基础 - 练习1
- 硬笔楷书26
- Python爬虫|Python爬虫 --- 1.4 正则表达式(re库)
- Python(pathlib模块)
- python青少年编程比赛_第十一届蓝桥杯大赛青少年创意编程组比赛细则
- Python数据分析(一)(Matplotlib使用)