软硬件环境

  • windows 11 64bits

  • python 3.6

  • 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
import time
@retry
def task():
print("task running ... ")
time.sleep(1)
raise Exception
task()

执行上述代码,得到

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次

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

重试三次之后就报错了

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

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

一直重试很多次,3秒后还没成功,就结束重试

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

import time
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 ... ")
time.sleep(1)
raise Exception
task()

设定等待时间

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

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

如下,可以看到,每隔3秒重试一次

使用方法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 Exception
task()

时间有1 2 3s的

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

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

什么情况下重试

可以通过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 Exception
task()

重试错误后的异常抛出

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

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

默认是false,false是重试错误

在重试前执行动作

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

from tenacity import retry, stop_after_attempt, before_log
import logging
import sys
logging.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 Exception
task()

tenacity重试后的操作类似,如下

from tenacity import retry, stop_after_attempt, after_log
import logging
import sys
logging.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 Exception
task()

tenacity

Python实用模块专题

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

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

参考资料

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

http://www.taodudu.cc/news/show-4122770.html?action=onClick

Python重试任务模块tenacity的更多相关文章

  1. Python重试模块retrying

    Python重试模块retrying 工作中经常碰到的问题就是,某个方法出现了异常,重试几次.循环重复一个方法是很常见的.比如爬虫中的获取代理,对获取失败的情况进行重试. 刚开始搜的几个博客讲的有点问 ...

  2. python之platform模块

    python之platform模块 ^_^第三个模块从天而降喽!! 函数列表 platform.system() 获取操作系统类型,windows.linux等 platform.platform() ...

  3. python之OS模块详解

    python之OS模块详解 ^_^,步入第二个模块世界----->OS 常见函数列表 os.sep:取代操作系统特定的路径分隔符 os.name:指示你正在使用的工作平台.比如对于Windows ...

  4. python之sys模块详解

    python之sys模块详解 sys模块功能多,我们这里介绍一些比较实用的功能,相信你会喜欢的,和我一起走进python的模块吧! sys模块的常见函数列表 sys.argv: 实现从程序外部向程序传 ...

  5. 学习PYTHON之路, DAY 6 - PYTHON 基础 6 (模块)

    一 安装,导入模块 安装: pip3 install 模块名称 导入: import module from module.xx.xx import xx from module.xx.xx impo ...

  6. linux下python调用c模块

    在C调用Python模块时需要初始化Python解释器,导入模块等,但Python调用C模块却比较简单,下面还是以helloWorld.c 和 main.py 做一说明:   (1)编写C代码,hel ...

  7. Python学习之模块进程函数详解

    今天在看<Beginning Linux Programming>中的进程相关部分,讲到Linux几个进程相关的系统函数: system , exec , fork ,wait . Pyt ...

  8. python基础——第三方模块

    python基础——第三方模块 在Python中,安装第三方模块,是通过包管理工具pip完成的.  如果你正在使用Mac或Linux,安装pip本身这个步骤就可以跳过了.  如果你正在使用Window ...

  9. python基础——使用模块

    python基础——使用模块 Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用. 我们以内建的sys模块为例,编写一个hello的模块: #!/usr/bin/env ...

  10. python 中time模块使用

    在开始之前,首先要说明这几点: 1.在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串 3)元组(struct_time)共九个元素.由于Python的time模块实现主 ...

随机推荐

  1. 聊聊ChatGLM3多用户并发API调用的问题

    转载请备注出处:https://www.cnblogs.com/zhiyong-ITNote 背景 目前在公司内部4张A10的GPU服务器上部署了ChatGLM3开源模型:然后部署了官方默认的web_ ...

  2. 视频播放测试地址(MP4、M3U8 格式)

    最近在开发视频播放相关的业务功能,开发测试时,需要涉及到 MP4.M3U8 等视频格式. 我每次找测试视频地址时,都要找很久,现在把我在网上收集到的 MP4.M3U8 格式视频地址放在这里,希望帮助到 ...

  3. 第十五篇:JavaScript 之 Dom操作

    一.后台管理页面布局 主站布局 <div class="pg-header"></div> <div style="width:980px; ...

  4. stmp 501 5.1.3 Invalid Address 无效的邮件地址

    stmp 501 5.1.3 Invalid Address 无效的邮件地址 一般来说就是要确认邮箱地址是不是对的 还有一种可能的情况是使用的邮件服务器仅支持对内邮件,没有对外邮件的发送权限

  5. selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH.的解决办法

    跟着视频学习python爬取网页信息,结果出现如下问题: 在网页上搜索各种资料,最终解决该问题,所以记录一下: 1.查看自己浏览器的版本号,点击"三个点--帮助--关于Google Chro ...

  6. Java 应用压测性能问题定位经验分享

    简介: 问题千千万,但只要修练了足够深厚的内功,形成一套属于自己的排查问题思路和打法,再加上一套支撑问题排查的工具,凭借已有的经验还有偶发到来的那一丝丝灵感,相信所有的问题都会迎刃而解. 作者:凡勇 ...

  7. Serverless Kubernetes:理想,现实与未来

    简介: 当前 Serverless 容器的行业趋势如何?有哪些应用价值?如果 Kubernetes 天生长在云上,它的架构应该如何设计?Serverless 容器需要哪些基础设施?阿里云容器服务产品负 ...

  8. 基于 Serverless 打造如 Windows 体验的个人专属家庭网盘

    ​简介:虽然现在市面上有些网盘产品, 如果免费试用,或多或少都存在一些问题, 可以参考文章<2020 国内还能用的网盘推荐>.本文旨在使用较低成本打造一个 "个人专享的.无任何限 ...

  9. Quick Audience组织和工作空间功能解读

    近期,Quick Audience完成了权限系统全面升级,可以解决集团企业不同品牌.不同运营组织,不同消费者运营的诉求,精细化保障企业数据访问安全,提升管控的灵活度.​ Quick Audience整 ...

  10. Nacos 2.0 升级前后性能对比压测

    简介: Nacos 2.0 通过升级通信协议和框架.数据模型的方式将性能提升了约 10 倍,解决继 Nacos 1.0 发布逐步暴露的性能问题.本文通过压测 Nacos 1.0,Nacos 1.0 升 ...