首页 > 编程语言 >python retry feature

python retry feature

时间:2023-02-13 15:23:38浏览次数:42  
标签:giveup retry return python exception feature backoff wait

简单的retry 功能有两种实现方法

  • retry module - 可以实现简单的retry, 指定retry 次数。
  • backoff module - 相对于retry 模块, 功能更丰富一点。 
retry example
1 @retry(InvalidLogin, tries=2, delay=0)
2 @retry(httpx.ConnectError, tries=5, delay=2) # decorator 可以嵌套使用
3 def get(cls, endpoint: str):
4     。。。。
View Code

backoff example

1 @backoff.on_exception(
2     backoff.constant,
3     Exception,
4     max_tries=3,
5     giveup=fatal_code,
6     on_backoff=backoff_fun,
7 )
8 def test2():
9    ...
View Code

通过查看backoff onexception 的signature, 学习下用法啊

"""Returns decorator for backoff and retry triggered by exception.


Args:
    wait_gen: A generator yielding successive wait times in
        seconds. ## 一个generator, 可以before retry需要等待的时间。
    exception: An exception type (or tuple of types) which triggers
        backoff. # 显而易见, exception or tuple of exception
    max_tries: The maximum number of attempts to make before giving
        up. Once exhausted, the exception will be allowed to escape.
        The default value of None means there is no limit to the
        number of tries. If a callable is passed, it will be
        evaluated at runtime and its return value used.
    max_time: The maximum total amount of time to try for before
        giving up. Once expired, the exception will be allowed to
        escape. If a callable is passed, it will be
        evaluated at runtime and its return value used.
    jitter: A function of the value yielded by wait_gen returning
        the actual time to wait. This distributes wait times
        stochastically in order to avoid timing collisions across
        concurrent clients. Wait times are jittered by default
        using the full_jitter function. Jittering may be disabled
        altogether by passing jitter=None.
    giveup: Function accepting an exception instance and
        returning whether or not to give up. Optional. The default
        is to always continue.  # giveup=fatal_code
```
def fatal_code(e): # 入参是exception instance
    # return type(e) == 'TypeError'
    e_type = type(e)
    logger.info(f"Give up code. error is - {e_type} - {str(e)} ..")
    return 0 # 返回0 or 1, 0: retry 继续, 不giveup
```
    on_success: Callable (or iterable of callables) with a unary
        signature to be called in the event of success. The
        parameter is a dict containing details about the invocation.
    on_backoff: Callable (or iterable of callables) with a unary
        signature to be called in the event of a backoff. The
        parameter is a dict containing details about the invocation.
```
这三个on function, 都是类似的用法, backoff的时候做什么, 用法on_backoff=backoff_fun
def backoff_fun(detail): # detail is a dict, 包括你需要的所有的东西
    logger.info(f"backoff function {detail}")
    return 1
```
    on_giveup: Callable (or iterable of callables) with a unary
        signature to be called in the event that max_tries
        is exceeded.  The parameter is a dict containing details
        about the invocation.
    raise_on_giveup: Boolean indicating whether the registered exceptions
        should be raised on giveup. Defaults to `True`
    logger: Name or Logger object to log to. Defaults to 'backoff'.
    backoff_log_level: log level for the backoff event. Defaults to "INFO"
    giveup_log_level: log level for the give up event. Defaults to "ERROR"
    **wait_gen_kwargs: Any additional keyword args specified will be
        passed to wait_gen when it is initialized.  Any callable
        args will first be evaluated and their return values passed.
        This is useful for runtime configuration.

 

标签:giveup,retry,return,python,exception,feature,backoff,wait
From: https://www.cnblogs.com/hello-pyworld/p/17116483.html

相关文章

  • python画图的简单案例
    #导包frompyecharts.chartsimportLinefrompyecharts.optionsimportTitleOpts,ToolboxOpts,LegendOpts,VisualMapOpts#创建一个折线图像对象,即创建一个空的坐标系line......
  • python 导包失败:--ImportError: No module named XXXX
    问题Traceback(mostrecentcalllast):File"/home/app/auto_train/scripts/train_auto/train_auto.py",line5,in<module>frommonitorimportyarn_monitorIm......
  • Python缓存机制
    1.什么是缓存机制Python对象在创建的时候,会为其开辟一个内存,当变量引用该对象时,实际上是指向该对象的内存地址,当该对象不在被引用,会被垃圾回收机制回收,释放内存。但......
  • python datetime 时间模块
    datetime.now()会得到当前时间,datetime.datetime(2023,2,13,17,24,29,309381currentDateAndTime=datetime.now()print(f'Time:{currentDateAndTime.year}/{cur......
  • python中的模块调用案例
    此案例是本人在B站上学习“黑马程序员”up主的课,课程中一个案例特别好,在此记录一下。在创建包的时候,会产生一个__init__.py文件,如果没有这个文件,那么就是生成的普通文件夹。......
  • python自动化办公--pyautogui控制鼠标和键盘操作
    ✅作者简介:热爱科研的算法开发者,Python、Matlab项目可交流、沟通、学习。 ......
  • python基础之字符串处理
     ✅作者简介:热爱科研的算法开发者,Python、Matlab项目可交流、沟通、学习。 ......
  • Python常见面试题(持续更新 23-2-13)
    Python常见面试题(持续更新23-2-13)参考资料https://github.com/taizilongxu/interview_pythonhttps://github.com/hantmac/Python-Interview-Customs-Collectionhtt......
  • Macbook macOS安装Python虚拟开发环境virtualenv
    由于各种工具包版本兼容性问题,pip安装到虚拟环境比较方便管理版本、依赖、更新、测试等。打开终端,安装pipinstallvirtualenv或者apt-getinstallvirtualenv查看版......
  • 多变量两两相互关系联合分布图的Python绘制
      本文介绍基于Python中seaborn模块,实现联合分布图绘制的方法。  联合分布(JointDistribution)图是一种查看两个或两个以上变量之间两两相互关系的可视化图,在数据分析......