易于使用的重试装饰器。

retr的Python项目详细描述


https://pypip.in/d/retry/badge.pnghttps://pypip.in/v/retry/badge.pnghttps://pypip.in/license/retry/badge.png

易于使用的重试装饰器。

功能

  • 无外部依赖关系(仅限stdlib)。
  • (可选)保留函数签名(pip install decorator)。
  • 原始回溯,易于调试。

安装

$ pip install retry

API

重试decorator

defretry(exceptions=Exception,tries=-1,delay=0,max_delay=None,backoff=1,jitter=0,logger=logging_logger):"""Return a retry decorator.

    :param exceptions: an exception or a tuple of exceptions to catch. default: Exception.
    :param tries: the maximum number of attempts. default: -1 (infinite).
    :param delay: initial delay between attempts. default: 0.
    :param max_delay: the maximum value of delay. default: None (no limit).
    :param backoff: multiplier applied to delay between attempts. default: 1 (no backoff).
    :param jitter: extra seconds added to delay between attempts. default: 0.
                   fixed if a number, random if a range tuple (min, max)
    :param logger: logger.warning(fmt, error, delay) will be called on failed attempts.
                   default: retry.logging_logger. if None, logging is disabled.
    """

各种重试逻辑可以通过参数的组合来实现。

示例

fromretryimportretry
@retry()defmake_trouble():'''Retry until succeed'''
@retry(ZeroDivisionError,tries=3,delay=2)defmake_trouble():'''Retry on ZeroDivisionError, raise error after 3 attempts, sleep 2 seconds between attempts.'''
@retry((ValueError,TypeError),delay=1,backoff=2)defmake_trouble():'''Retry on ValueError or TypeError, sleep 1, 2, 4, 8, ... seconds between attempts.'''
@retry((ValueError,TypeError),delay=1,backoff=2,max_delay=4)defmake_trouble():'''Retry on ValueError or TypeError, sleep 1, 2, 4, 4, ... seconds between attempts.'''
@retry(ValueError,delay=1,jitter=1)defmake_trouble():'''Retry on ValueError, sleep 1, 2, 3, 4, ... seconds between attempts.'''
# If you enable logging, you can get warnings like 'ValueError, retrying in# 1 seconds'if__name__=='__main__':importlogginglogging.basicConfig()make_trouble()

重试呼叫

defretry_call(f,fargs=None,fkwargs=None,exceptions=Exception,tries=-1,delay=0,max_delay=None,backoff=1,jitter=0,logger=logging_logger):"""
    Calls a function and re-executes it if it failed.

    :param f: the function to execute.
    :param fargs: the positional arguments of the function to execute.
    :param fkwargs: the named arguments of the function to execute.
    :param exceptions: an exception or a tuple of exceptions to catch. default: Exception.
    :param tries: the maximum number of attempts. default: -1 (infinite).
    :param delay: initial delay between attempts. default: 0.
    :param max_delay: the maximum value of delay. default: None (no limit).
    :param backoff: multiplier applied to delay between attempts. default: 1 (no backoff).
    :param jitter: extra seconds added to delay between attempts. default: 0.
                   fixed if a number, random if a range tuple (min, max)
    :param logger: logger.warning(fmt, error, delay) will be called on failed attempts.
                   default: retry.logging_logger. if None, logging is disabled.
    :returns: the result of the f function.
    """

这与decorator非常相似,只是它将函数及其参数作为参数。它背后的用例是能够动态地调整重试参数。

importrequestsfromretry.apiimportretry_calldefmake_trouble(service,info=None):ifnotinfo:info=''r=requests.get(service+info)returnr.textdefwhat_is_my_ip(approach=None):ifapproach=="optimistic":tries=1elifapproach=="conservative":tries=3else:# skepticaltries=-1result=retry_call(make_trouble,fargs=["http://ipinfo.io/"],fkwargs={"info":"ip"},tries=tries)print(result)what_is_my_ip("conservative")

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java如何处理可以为null或整数的POJO类值   JavaFXSpring类NotFoundException:org。springframework。上下文注释。注释ConfigApplicationContext   java Jackson JSON不包装嵌套对象的属性   编写多个SQL查询的java最佳实践   安卓 java。lang.IllegalStateException:无法提取AndroidPlatform、sslSocketFactory上的信任管理器   MongoDB/Morphia将技术id保存为ObjectId,尽管它在Java中是一个字符串   JavaEclipse只加载log4。测试文件夹中的属性   java如何通过次对角线遍历2D数组?   java在geotools jmappane中制作shapefile编辑器   数组如何在java中获得表大小2^32   java API调试。如何查找函数体之前发生的错误?   java如何创建二维数组,其中#1位于随机位置,并执行特定次数   java文本文件比较   java SDK支持diff spring版本   javaspring引导集成测试javax。坚持不懈PersistenceException:org。冬眠PersistentObject异常