Python重试库 Tenacity 推荐

2023-10-15 04:30
文章标签 python 推荐 重试 tenacity

本文主要是介绍Python重试库 Tenacity 推荐,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Python重试库 Tenacity 推荐

文章目录

  • Python重试库 Tenacity 推荐
    • 1 Tenacity描述
    • 2 如果发生异常就重试
    • 3 设置停止重试的条件
      • 设置重试的最大次数
      • 还可以设置stop 时间
      • 停止重试条件 进行组合
    • 4 设置重试的间隔
    • 5 重试触发的条件
      • 针对具体的异常进行重试
      • 针对函数的返回结果进行重试
    • 6 定义重试失败回调函数
    • 7 错误处理
    • 8 推荐看下 作者的对这个库介绍
    • Python never gives up: the tenacity library
    • Basic usage
    • Combination
    • Standalone usage
    • 参考地址

1 Tenacity描述

今天 给大家介绍一个Python 重试库,Tenacity 这个库 是我 这些年 使用的一个非常好的库,几乎满足了我所有的重试需求,非常棒的一个库。

在我们日常开发中,我们经常会遇到 网络问题 或者其他问题,导致 API请求失败,或者超时等出现, 这个出现是偶发性,不确定性的,我们如何保证系统的功能的正确性呢? 第一种 显示 告诉 用户请求失败。 第二种 我们可以通过重试 几次 看看会不会成功,如果 能成功 就可以了。

因此在真实的项目开发中重试的库,也显得 尤其重要, 在工作中 我也有尝试写过一些 重试的装饰器函数,总感觉 差点意思,要不就是 考虑不全面,要么就是 实现太简单 ,不能针对具体的异常进行重试,不能设置一些条件重试等。 以及重试 还是失败了怎么处理? 等等一系列的问题。

直到后来发现这个 宝藏库 tenacity ,几乎解决了我所有的痛点。

一起来了解这个库的基本用法

2 如果发生异常就重试

这个就是 如果发生了异常就一直重试下去

from tenacity import retry, stop_after_attempt@retry()
def never_gonna_give_you_up():print("Retry forever ignoring Exceptions, don't wait between retries")raise Exception("Unknown Error")

3 设置停止重试的条件

设置重试的最大次数

这里设置最多重试5次 ,失败后 就不在进行重试了。

from tenacity import retry, stop_after_attempt@retry(stop=stop_after_attempt(5))
def never_gonna_give_you_up():print("Retry forever ignoring Exceptions, don't wait between retries")raise Exception("Unknown Error")if __name__ == '__main__':never_gonna_give_you_up()

还可以设置stop 时间

stop = stop_after_delay

Stop when the time from the first attempt >= limit 从第一次失败 尝试 到 多久后 停止尝试。

默认 stop_after_delay 单位是秒

import timefrom tenacity import retry, stop_after_delay@retry(stop=stop_after_delay(10))
def stop_after_10_s():print("10秒后停止重试")time.sleep(5)raise Exception("Unknown Error")if __name__ == '__main__':stop_after_10_s()

停止重试条件 进行组合

from tenacity import retry, stop_after_delay, stop_after_attempt@retry(stop=(stop_after_delay(10) | stop_after_attempt(5)))
def stop_after_10_s_or_5_retries():print("10秒后或者5次重试后停止重试")raise Exception("Unknown Error")if __name__ == '__main__':stop_after_10_s_or_5_retries()

4 设置重试的间隔

有的时候 重试 太频繁了,也不太好,可能因为 网络问题,过一段时间才能恢复好,

wait_fixed(seconds=10) 等几秒后重试, 然后 可以组合 stop 在一起使用。

from tenacity import retry, stop_after_attempt, wait_fixed@retry(stop=stop_after_attempt(3),wait=wait_fixed(3))
def never_gonna_give_you_up():print("Retry max attempt:3, wait_fixed:3")raise Exception("Unknown Error")if __name__ == '__main__':never_gonna_give_you_up()

5 重试触发的条件

针对具体的异常进行重试

对具体的异常进行重试 ,而不是所有异常进行重试. 有的时候 我们在写 业务代码的时候,可能会定义一些 自定义的异常,我们有时候 触发特定的异常 进行重试,而不是说 发生了异常 就进行 重试。 tenacity 这个库 早就想好了这点。

我自定义了一个异常 NotExistResourceErr , 触发这个异常我才进行重试,重试最多三次。

# -*- coding: utf-8 -*-from typing import Anyfrom tenacity import retry, stop_after_delay, stop_after_attempt, retry_if_exception_typeclass NotExistResourceErr(Exception):"""定义一个自定义的异常"""code = str(400)detail = "Parameter Error"def __init__(self, code: str = None, detail: Any = None):self.code = codeself.detail = detailclass Source:def __init__(self, id):self.id = id@retry(retry=retry_if_exception_type(NotExistResourceErr), stop=stop_after_attempt(3))
def might_exist_error(task_id: int = 0):print('might_exist_error begin ...')if task_id < 0:raise NotExistResourceErr()return Source(task_id)if __name__ == '__main__':might_exist_error(-10)

retry_if_exception_type 这里就告诉 tenacity 在发生什么类型,才进行重试操作。 设置 stop_after_attempt(3) 重试3 次就停止了。

运行一下结果如下: 可以看出 重试了三次,第三次后 抛出了异常

在这里插入图片描述

如果在里面 这样 抛出一个异常的话,此时 tenacity 不会进行重试操作,而是 程序直接报错。

@retry(retry=retry_if_exception_type(NotExistResourceErr), stop=stop_after_attempt(3))
def might_exist_error(task_id: int = 0):print('might_exist_error begin ...')if task_id < 0:raise Exception("Unknown Error")return Source(task_id)

如果这样的话, 不会进行重试操作 ,而是直接抛出了异常。

在这里插入图片描述

针对函数的返回结果进行重试

有的时候 可能因为 某些原因 正常情况下,应该可以获取到值,但是返回结果为None, 异常情况 在 函数内部进行捕获处理了,这个时候 也想进行 重试 怎么办呢?

retry_if_result 这里可以传入一个函数,这个函数接收 might_return_none 返回值, 然后 这个函数 返回 True 就会 触发重试操作。

from tenacity import retry, stop_after_attempt, retry_if_resultdef is_none(value):"""Return True if value is None"""return value is None@retry(retry=retry_if_result(is_none), stop=stop_after_attempt(3))
def might_return_none():print("返回 None 则重试")return Noneif __name__ == '__main__':might_return_none()

类似与此相反的 retry_if_not_result 当结果 不符合预期 则进行重试操作。

6 定义重试失败回调函数

对于重要的业务的话, 如果重试几次后, 发现仍然是失败的状态,此时 我们可以 设置 一个回调函数, 比如 在回调函数中 发一个邮件 通知 相关 的人员,手动处理异常,检查问题等。

retry_error_callback 这里可以传入一个回调 函数 , 回函函数中有一个参数 retry_state 最后一次 函数的返回的状态。

在回调函数中 可以做你想做的任何处理,发邮件 或者其他的操作。

from tenacity import stop_after_attempt, retry, retry_if_resultdef send_email(msg):print(msg)# 回调函数
def callback(retry_state):"""return the result of the last call attempt"""# print(f"call function ... {retry_state}, {type(retry_state)}")send_email('eventually_return_false eventually failed')return retry_state.outcome.result()def is_false(value):"""Return True if value is False"""return value is False# will return False after trying 3 times to get a different result
@retry(stop=stop_after_attempt(3),retry_error_callback=callback,retry=retry_if_result(is_false))
def eventually_return_false():print("failed ...")return Falseif __name__ == '__main__':eventually_return_false()pass

7 错误处理

有的时候 我们可能重试后失败了,想获取原来 程序代码中抛出 的异常。 我们可以使用 reraise 参数来 抛出异常。是一个bool 变量,

设置为True 会抛出原来的异常, 如果设置为False 则不会抛出原来的异常 ,会抛出 tenacity.RetryError

from tenacity import retry, stop_after_delay, stop_after_attempt, retry_if_exception_type, retry_if_resultclass NotExistResourceErr(Exception):"""定义一个自定义的异常"""code = str(400)detail = "Parameter Error"def __init__(self, code: str = None, detail: Any = None):self.code = code or self.codeself.detail = detail or self.detail@retry(reraise=True , stop=stop_after_attempt(3))
def raise_my_exception():raise NotExistResourceErr(detail="Fail",code='0000')try:raise_my_exception()
except NotExistResourceErr as e :print(f'handle exception detail:{e.detail} code:{e.code}')

设置为 reraise=False 整个程序 就会挂掉,如下面的报错

Traceback (most recent call last):File "/Users/frank/code/venv38/venv/lib/python3.8/site-packages/tenacity/__init__.py", line 407, in __call__result = fn(*args, **kwargs)File "/Users/frank/code/py_proj/study-fastapi/my_retry_demo/hello6.py", line 42, in raise_my_exceptionraise NotExistResourceErr("Fail")
__main__.NotExistResourceErr: FailThe above exception was the direct cause of the following exception:Traceback (most recent call last):File "/Users/frank/code/py_proj/study-fastapi/my_retry_demo/hello6.py", line 45, in <module>raise_my_exception()File "/Users/frank/code/venv38/venv/lib/python3.8/site-packages/tenacity/__init__.py", line 324, in wrapped_freturn self(f, *args, **kw)File "/Users/frank/code/venv38/venv/lib/python3.8/site-packages/tenacity/__init__.py", line 404, in __call__do = self.iter(retry_state=retry_state)File "/Users/frank/code/venv38/venv/lib/python3.8/site-packages/tenacity/__init__.py", line 361, in iterraise retry_exc from fut.exception()
tenacity.RetryError: RetryError[<Future at 0x7f990dddb4c0 state=finished raised NotExistResourceErr>]

8 推荐看下 作者的对这个库介绍

我做了一些翻译,感兴趣的同学 可以关注一下。

Python never gives up: the tenacity library 作者原文

Python never gives up: the tenacity library

A couple of years ago, I wrote about the Python retrying library. This library was designed to retry the execution of a task when a failure occurred.

几年前,我写过关于Python重试库的文章。这个库被设计用来在一个任务发生故障时重试执行。

I started to spread usage of this library in various projects, such as Gnocchi, these last years. Unfortunately, it started to get very hard to contribute and send patches to the upstream retrying project. I spent several months trying to work with the original author. But after a while, I had to conclude that I would be unable to fix bugs and enhance it at the pace I would like to. Therefore, I had to take a difficult decision and decided to fork the library.

在过去的几年里,我开始在各种项目中推广使用这个库,比如Gnocchi。不幸的是,向上游的retrying项目贡献和发送补丁开始变得非常困难。我花了几个月的时间试图与原作者合作。但一段时间后,我不得不得出结论,我将无法以我想要的速度来修复错误和增强它。因此,我不得不做出一个艰难的决定,决定fork这个库。

Here comes tenacity

I picked a new name and rewrote parts of the API of retrying that were not working correctly or were too complicated. I also fixed bugs with the help of Joshua, and named this new library tenacity. It works in the same manner as retrying does, except that it is written in a more functional way and offers some nifty new features.

tenacity 就这样诞生了,

我选了一个新的名字,并重写了重试的API中不能正确工作或过于复杂的部分。我还在Joshua的帮助下修复了一些错误,并将这个新的库命名为tenacity。它的工作方式与重试相同,只是它是以一种更实用的方式编写的,并提供一些有趣的新功能。

nifty /ˈnɪftɪ/

niftier 比较级

niftiest 最高级

    • ADJ If you describe something as nifty, you think it is neat and pleasing or cleverly done. 整洁而惹人喜爱的; 完成得精巧的

• Bridgeport was a pretty nifty place.

布里奇波特曾是个相当整洁、惹人喜爱的地方。

• It was a nifty arrangement, a perfect partnership.

这既是个绝佳的安排,又是个完美的合作。

Basic usage

The basic usage is to use it as a decorator:

import tenacity@tenacity.retry
def do_something_and_retry_on_any_exception():pass

This will make the function do_something_and_retry_on_any_exception be called over and over again until it stops raising an exception. It would have been hard to design anything simpler. Obviously, this is a pretty rare case, as one usually wants to e.g. wait some time between retries. For that, tenacity offers a large panel of waiting methods:

这将使函数do_something_and_retry_on_any_exception被反复调用,直到它停止引发异常。很难再设计出更简单的东西了。显然,这是一个相当罕见的情况,因为人们通常希望在重试之间等待一段时间。为此,tenacity提供了大量的等待方法。

import tenacity@tenacity.retry(wait=tenacity.wait_fixed(1))
def do_something_and_retry():do_something()

Or a simple exponential back-off method can be used instead:

或者可以用一个简单的指数回退法来代替。

import tenacity@tenacity.retry(wait=tenacity.wait_exponential())
def do_something_and_retry():do_something()

Combination

组合

What is especially interesting with tenacity, is that you can easily combine several methods. For example, you can combine tenacity.wait.wait_random with tenacity.wait.wait_fixed to wait a number of seconds defined in an interval:

tenacity特别有趣的是,你可以很容易地结合几种方法。例如,你可以把 tenacity.wait.wait_randomtenacity.wait.wait_fixed 结合起来,等待在一个时间间隔内定义的若干秒。

import tenacity@tenacity.retry(wait=tenacity.wait_fixed(10) + wait.wait_random(0, 3))
def do_something_and_retry():do_something()

This will make the function being retried wait randomly between 10 and 13 seconds before trying again.

这将使被重试的函数在再次尝试之前随机地等待10到13秒。

tenacity offers more customization, such as retrying on some exceptions only. You can retry every second to execute the function only if the exception raised by do_something is an instance of IOError, e.g. a network communication error.

tenacity提供了更多的自定义功能,比如只在某些异常情况下重试。你可以在do_something引发的异常是IOError的实例时,例如网络通信错误,才每秒重试执行函数。

import tenacity@tenacity.retry(wait=tenacity.wait_fixed(1),retry=tenacity.retry_if_exception_type(IOError))def do_something_and_retry():do_something()

You can combine several condition easily by using the | or & binary operators. They are used to make the code retry if an IOError exception is raised, or if no result is returned. Also, a stop condition is added with the stop keyword arguments. It allows to specify a condition unrelated to the function result of exception to stop, such as a number of attemps or a delay.

你可以通过使用|&二进制操作符轻松地组合几个条件。它们被用来在引发IOError异常或没有返回结果时使代码重试。此外,还可以用stop关键字参数添加一个停止条件。它允许指定一个与要停止的异常的函数结果无关的条件,例如尝试的次数或延迟。

import tenacity@tenacity.retry(wait=tenacity.wait_fixed(1),stop=tenacity.stop_after_delay(60),retry=(tenacity.retry_if_exception_type(IOError) |tenacity.retry_if_result(lambda result: result == None))
def do_something_and_retry():do_something()

The functional approach of tenacity makes it easy and clean to combine a lot of condition for various use cases with simple binary operators.

tenacity的函数式方法使得它可以很容易和干净地用简单的二进制运算符为各种使用情况组合大量的条件。

Standalone usage

独立使用

tenacity can also be used without decorator by using the object Retrying, which implements its main behavior and using its call method. This allows to call any function with different retry conditions, or to retry any piece of code that do not use the decorator at all – like code from an external library.

tenacity也可以在没有装饰器的情况下使用,通过使用Retrying对象,实现其主要行为并使用其调用方法。这允许调用任何具有不同重试条件的函数,或重试任何完全不使用装饰器的代码–如来自外部库的代码。

import tenacityr = tenacity.Retrying(wait=tenacity.wait_fixed(1),retry=tenacity.retry_if_exception_type(IOError))r.call(do_something)

This also allows you to re-use that object without creating one new one each time, saving some memory!

这也允许你重复使用该对象,而不需要每次都创建一个新的对象,从而节省一些内存。

I hope you’ll like it and will find it of some use. Feel free to fork it, report bugs, or ask for new features on its GitHub!

我希望你会喜欢它,并会发现它有一些用处。欢迎在GitHub上分享它,报告错误,或要求提供新的功能。

If you want to learn more about retrying strategy and how to handle failure, there’s even more in Scaling Python. Check it out!

如果你想了解更多关于重试策略和如何处理失败,在Scaling Python中有更多内容。请看它!

参考地址

tenacity github

Python never gives up: the tenacity library 作者原文

少有人知的 Python “重试机制”,详解 tenacity 的使用

python重试库-tenacity 使用指南

分享快乐,留住感动. '2022-08-13 18:58:40' --frank

这篇关于Python重试库 Tenacity 推荐的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/215333

相关文章

不懂推荐算法也能设计推荐系统

本文以商业化应用推荐为例,告诉我们不懂推荐算法的产品,也能从产品侧出发, 设计出一款不错的推荐系统。 相信很多新手产品,看到算法二字,多是懵圈的。 什么排序算法、最短路径等都是相对传统的算法(注:传统是指科班出身的产品都会接触过)。但对于推荐算法,多数产品对着网上搜到的资源,都会无从下手。特别当某些推荐算法 和 “AI”扯上关系后,更是加大了理解的难度。 但,不了解推荐算法,就无法做推荐系

python: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

深入探索协同过滤:从原理到推荐模块案例

文章目录 前言一、协同过滤1. 基于用户的协同过滤(UserCF)2. 基于物品的协同过滤(ItemCF)3. 相似度计算方法 二、相似度计算方法1. 欧氏距离2. 皮尔逊相关系数3. 杰卡德相似系数4. 余弦相似度 三、推荐模块案例1.基于文章的协同过滤推荐功能2.基于用户的协同过滤推荐功能 前言     在信息过载的时代,推荐系统成为连接用户与内容的桥梁。本文聚焦于

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学

防近视护眼台灯什么牌子好?五款防近视效果好的护眼台灯推荐

在家里,灯具是属于离不开的家具,每个大大小小的地方都需要的照亮,所以一盏好灯是必不可少的,每个发挥着作用。而护眼台灯就起了一个保护眼睛,预防近视的作用。可以保护我们在学习,阅读的时候提供一个合适的光线环境,保护我们的眼睛。防近视护眼台灯什么牌子好?那我们怎么选择一个优秀的护眼台灯也是很重要,才能起到最大的护眼效果。下面五款防近视效果好的护眼台灯推荐: 一:六个推荐防近视效果好的护眼台灯的

智能交通(二)——Spinger特刊推荐

特刊征稿 01  期刊名称: Autonomous Intelligent Systems  特刊名称: Understanding the Policy Shift  with the Digital Twins in Smart  Transportation and Mobility 截止时间: 开放提交:2024年1月20日 提交截止日

nudepy,一个有趣的 Python 库!

更多资料获取 📚 个人网站:ipengtao.com 大家好,今天为大家分享一个有趣的 Python 库 - nudepy。 Github地址:https://github.com/hhatto/nude.py 在图像处理和计算机视觉应用中,检测图像中的不适当内容(例如裸露图像)是一个重要的任务。nudepy 是一个基于 Python 的库,专门用于检测图像中的不适当内容。该

pip-tools:打造可重复、可控的 Python 开发环境,解决依赖关系,让代码更稳定

在 Python 开发中,管理依赖关系是一项繁琐且容易出错的任务。手动更新依赖版本、处理冲突、确保一致性等等,都可能让开发者感到头疼。而 pip-tools 为开发者提供了一套稳定可靠的解决方案。 什么是 pip-tools? pip-tools 是一组命令行工具,旨在简化 Python 依赖关系的管理,确保项目环境的稳定性和可重复性。它主要包含两个核心工具:pip-compile 和 pip