软硬件环境

  • windows 10 64bits

  • anaconda with python 3.7

  • tenacity

简介

在实际应用中,经常会碰到在web请求时,因为网络的不稳定,会有请求超时的问题,这时候,一般都是自己去实现重试请求的逻辑,直到得到响应或者超时。虽然这样的逻辑并不复杂,但是代码写起来却不那么优雅,不那么pythonic

tenacity是一个重试库,使用python语言编写,它能够让我们在任务的重试操作中变得非常简单,使用的是Apache 2.0开源协议。

tenacity有如下特性

  • 装饰器API

  • 可指定停止条件

  • 可指定等待条件

  • 自定义异常时的重试

  • 自定义特定返回值的重试

  • 在协程中使用

模块安装

使用pip安装tenacity

pip install tenacity

示例代码

无条件重试

这是tenacity最基本的用法,在task方法中使用装饰器@retry,当task出现异常时,我们就重新运行task,这里没加任何限制,如果异常一直出现,task就会一直运行下去

from tenacity import retry@retry
def task():print("task running ... ")raise Exceptiontask()

执行上述代码,得到

task running ...
task running ...
task running ...
task running ...
task running ...
task running ...
task running ...
task running ...
task running ...
task running ...
task running ...
task running ...
task running ...
.
.
.

设定停止条件

通过方法stop_after_attempt指定重试的次数,如下的3次

from tenacity import retry, stop_after_attempt@retry(stop=stop_after_attempt(3))
def task():print("task running ... ")raise Exceptiontask()

或者使用方法stop_after_delay指定重试多长时候后停止,如下的3秒

from tenacity import retry, stop_after_delay@retry(stop=stop_after_delay(3))
def task():print("task running ... ")raise Exceptiontask()

还可以将stop_after_delaystop_after_attempt组合起来用,如下的代码,只要其中一个条件满足,task就停止运行

from tenacity import retry, stop_after_attempt, stop_after_delay@retry(stop=(stop_after_delay(10) | stop_after_attempt(5)))
def task():print("task running ... ")raise Exceptiontask()

设定等待时间

使用方法wait_fixed来指定重试时等待的时间,如下代码中的3秒,每一次重试task前都要等待3秒钟

from tenacity import retry, wait_fixed@retry(wait=wait_fixed(3))
def task():print("task running ... ")raise Exceptiontask()

使用方法wait_random(min, max),在minmax之间随机取值,每一次task重试前就等待这个随机值,单位是秒

from tenacity import retry, wait_random@retry(wait=wait_random(min=1, max=3))
def task():print("task running ... ")raise Exceptiontask()

当然,上面2中种方法也是可以结合起来用的

from tenacity import retry, wait_fixed, wait_random@retry(wait=wait_fixed(3) + wait_random(0, 2))
def task():print("task running ... ")raise Exceptiontask()

什么情况下重试

可以通过retry_if_exception_type指定特定类型的异常出现时,任务才重试

from tenacity import retry, retry_if_exception_type@retry(retry=retry_if_exception_type(IOError))
def task():print("task running ... ")raise Exceptiontask()

重试错误后的异常抛出

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

from tenacity import retry, stop_after_attempt@retry(stop=stop_after_attempt(3), reraise=True)
def task():print("task running ... ")raise Exceptiontask()

tenacity

在重试前执行动作

tenacity可以在任务重试前后执行某些动作,这里以加日志为例

from tenacity import retry, stop_after_attempt, before_log
import logging
import syslogging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logger = logging.getLogger(__name__)@retry(stop=stop_after_attempt(3), before=before_log(logger=logger, log_level=logging.DEBUG))
def task():print("task running ... ")raise Exceptiontask()

tenacity

重试后的操作类似,如下

from tenacity import retry, stop_after_attempt, after_log
import logging
import syslogging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logger = logging.getLogger(__name__)@retry(stop=stop_after_attempt(3), after=after_log(logger=logger, log_level=logging.DEBUG))
def task():print("task running ... ")raise Exceptiontask()

tenacity

Python实用模块专题

更多有用的python模块,请移步

https://xugaoxiang.com/category/python/modules/

参考资料

  • https://github.com/jd/tenacity

Python实用模块(二十四)tenacity相关推荐

  1. python四大软件-Python实用模块(二十)Apscheduler

    软硬件环境 windows 10 64bits anaconda with python 3.7 视频看这里 前言 说起定时任务,第一反应应该是windows自带的计划任务或者linux自带的cron ...

  2. Python实用模块(二十二)easydict

    软硬件环境 windows 10 64bit anaconda3 with python 3.7 easydict 1.9 前言 easydict能够让我们使用.操作符,就像访问属性attribute ...

  3. JAVASE基础模块二十四(泛型)

    JAVASE基础模块二十四(泛型) 泛型的引出 我们这样定义一个obj类的时候 使用的时候需要向下转型 会很麻烦 public class Fananan {public static void ma ...

  4. python接口自动化测试二十四:上传多个附件,参数化

    python接口自动化测试二十四:上传多个附件,参数化 # 添加多个附件参数化files = [("1.png", "1.png") ("2.png& ...

  5. Appium+python自动化(二十四)- 白素贞千年等一回许仙 - 元素等待(超详解)

    简介 许仙小时候最喜欢吃又甜又软的汤圆了,一次一颗汤圆落入西湖,被一条小白蛇衔走了.十几年后,一位身着白衣.有青衣丫鬟相伴的美丽女子与许仙相识了,她叫白娘子.白娘子聪明又善良,两个人很快走到了一起.靠 ...

  6. Python基础(二十四):面向对象核心知识

    文章目录 面向对象核心知识 一.面向对象三大特性 1.封装 2.继承 3.多态 二.多态 1.了解多态 2.体验多态 三.类属性和实例属性 1.类属性 2.实例属性 四.类方法和静态方法 1.类方法 ...

  7. Python实用模块(二十一)base64

    软硬件环境 windows 10 64bits anaconda with python 3.7 base64 flask 1.1.2 前言 图片处理是Python编程中需要掌握的基本技能,而pyth ...

  8. python爬虫(二十四)爬取汽车之家某品牌图片

    爬取汽车之家某品牌图片 需求 爬取汽车之家某品牌的汽车图片 目标url https://car.autohome.com.cn/photolist/series/52880/6957393.html# ...

  9. Python学习日记(二十四) 继承

    继承 什么是继承?就是一个派生类(derived class)继承基类(base class)的字段和方法.一个类可以被多个类继承;在python中,一个类可以继承多个类. 父类可以称为基类和超类,而 ...

  10. 【Python学习系列二十四】scikit-learn库逻辑回归实现唯品会用户购买行为预测

    1.背景:http://www.datafountain.cn/#/competitions/260/intro DataFountain上的唯品会用户购买行为预测比赛题目,笔者用逻辑回归实现,分数是 ...

最新文章

  1. 如何使用 Ansible 和 anacron 实现自动化
  2. 如何将程序添加到系统服务实现开机自启动
  3. PAT甲级——1102 Invert a Binary Tree (层序遍历+中序遍历)
  4. sublimelinter校验php,代码校验工具 SublimeLinter 的安装与使用
  5. 前端性能调优之Yahoo--23条
  6. shell:syntax error:unexpected end of file/Starting proxy www-balancer: cannot bind socket--转载
  7. 服务拆分-案例Demo
  8. 一个SAP成都研究院开发工程师 2020 年的所有文章列表
  9. 构件之法读书笔记04
  10. 使用动态代理解决网站字符集编码问题:(之前通过拦截器)
  11. 利用SciTE的导出功能保持代码语法着色效果
  12. Android 获取静态上下文(Application)
  13. Linux中vi、vim命令大全
  14. 多关键字排序的c语言编程,常见排序——“计数排序(三关键字)”的源程序(C语言版)...
  15. 基于深度学习生成音乐(mid格式)
  16. matlab中counter怎么用,matlab中fspecial函数的用法
  17. win10网络重置后,网卡驱动消失且装不上驱动的以及驱动带感叹号的解决办法
  18. 人人都能学会系列之ThreadLocal
  19. (转)卡马克卷轴算法研究
  20. 数据库应用----Mongodb 4.0 版本 基础操作---复制集,选举方法、部署认证 (二)

热门文章

  1. CUDA中的数学函数
  2. 含有ex的linux自动化工具,增加Linux自动化(RH294)和红帽认证工程师考试(EX294),附介绍...
  3. 在线绘制网络拓扑图操作方法分享
  4. 编写一个程序对Largest函数进行测试,找出一组数据的最大值
  5. 职场新人如何快速赚到自己的第一桶金?
  6. SAP中 关于BAPI_MATERIAL_SAVEDATA创建物料报错:字段MARA-MEINS/BAPI_MARA-BASE_UOM(_ISO)被定义为必需的字段; 它不包含条目
  7. 【图片resize】图片三种缩放方式/letterbox_image实现
  8. 【OpenGL】绘制四边形
  9. 华为三层交换机路由配置案例_华为三层交换与路由配置
  10. 深度学习基础6(微分,偏导,梯度,链式法则)