实现一个重试装饰器

class retry(object):    """A retry decorator."""

def __init__(self,                 exception=Exception,                 timeout=None,                 retries=None,                 interval=0.001,                 logfun=lambda s: print(s, file=sys.stderr),                 ):        if timeout and retries:            raise ValueError("timeout and retries args are mutually exclusive")        self.exception = exception        self.timeout = timeout        self.retries = retries        self.interval = interval        self.logfun = logfun

def __iter__(self):        if self.timeout:            stop_at = time.time() + self.timeout            while time.time() < stop_at:                yield        elif self.retries:            for _ in range(self.retries):                yield        else:            while True:                yield

def sleep(self):        if self.interval is not None:            time.sleep(self.interval)

def __call__(self, fun):        @functools.wraps(fun)        def wrapper(*args, **kwargs):            exc = None            for _ in self:                try:                    return fun(*args, **kwargs)                except self.exception as _:                    exc = _                    if self.logfun is not None:                        self.logfun(exc)                    self.sleep()                    continue            if PY3:                raise exc            else:                raise

# This way the user of the decorated function can change config        # parameters.        wrapper.decorator = self        return wrapper
def retry_before_failing(retries=NO_RETRIES):    """Decorator which runs a test function and retries N times before    actually failing.    """    return retry(exception=AssertionError, timeout=None, retries=retries)
@retry_before_failing()def test():  pass

原文地址:https://www.cnblogs.com/yaoguoguo/p/9961240.html

时间: 2024-08-02 22:11:30

实现一个重试装饰器的相关文章

一个图片装饰器的制作

一个图片装饰器的制作一1 首先创建工程picDecor,2 然后从对象库中,拉出Round Rect按钮到视图中,3 为了显示用户所选择的图片,需要往视图里, 添加view Controller对象,如下图4 还要一个图片视图imageView来编辑一张图片和一个windows and Bars工具栏来放置按钮,(备注:要先添加工具栏再添加iamgeView对像)5 再添加flexible space bar Button Item到工具栏中心,然后再添加一个bar buttonItem到工具栏

(转)实现一个cache装饰器,实现过期可清除功能

原文:http://www.cnblogs.com/JerryZao/p/9574927.html http://blog.51cto.com/11281400/2107790-----装饰器应用练习 文件私聊下载 灵感来自 from functools import lru_cache 的源代码,_make_key 1 ''' 实现一个cache 装饰器,实现可过期被清除的功能''' 2 3 # 第一步,实现了 与参数输入不同,也就是说,传入值后, 4 # 不管什么样子,只要传入的顺序一样,结

python重试装饰器的简单实现

简单实现了一个在函数执行出现异常时自动重试的装饰器,支持控制最多重试次数,每次重试间隔,每次重试间隔时间递增. 核心代码20行不到,最新的代码可以访问从github上获取 https://github.com/blackmatrix7/matirx-tookit/blob/master/decorator/retry.py #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/8/24 20:36 # @Author : Bla

一个函数装饰器

Python的函数是对象 Python  函数可以被赋值def  hello():–print('hello!') a = hello       #注: 此处没有() ,是一个对象 a()        # 调用a() 结果与hello() 相同 此时删除 hello,a() 依然保持原属性 函数可以定义在另一个函数里面 def say(): def hello(): return 'hello' return hello 外层的say函数会把内层的 hello函数的执行结果输出 函数可以返回

实现一个Porperty装饰器,可以把方法装饰成同一个属性名

今天简单的实现下Porperty装饰器demo: class Porperty: def __init__(self, fget= None, fset= None, fdel = None): self.fget= fget self.fset = fset self.fdel = fdel def __get__(self, instance, cls): if instance is None: return self if not callable(self.fget): raise A

装饰器、迭代器、生成器

1 def outer(func): 2 #func =原来f1函数 3 def inner(): 4 print('hio') 5 print('hio') 6 print('hio') 7 print('hio') 8 r=func() 9 print('1234214o') 10 print('1234214o') 11 print('1234214o') 12 print('1234214o') 13 14 return r 15 return inner 16 17 @outer 18

Python装饰器详解

装饰器简介: 装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象.它经常用于有切面需求的场景,比如:插入日志.性能测试.事务处理.缓存.权限校验等场景.装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量与函数功能本身无关的雷同代码并继续重用. 一个简单装饰器写法: 在写装饰器之前我们需要简单了解下python语法糖@的用法 http://www.cnblogs.com/Egbertbaron/p/72425

理解Python中的装饰器

文章先由stackoverflow上面的一个问题引起吧,如果使用如下的代码: @makebold @makeitalic def say(): return "Hello" 打印出如下的输出: <b><i>Hello<i></b> 你会怎么做?最后给出的答案是: def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>&q

Python装饰器与面向切面编程

今天来讨论一下装饰器.装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志.性能测试.事务处理等.装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数功能本身无关的雷同代码并继续重用.概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能. 1. 装饰器入门 1.1. 需求是怎么来的? 装饰器的定义很是抽象,我们来看一个小例子. 1 2 3 4 def foo():     print 'in foo()' foo() 这是一个很无聊的函数没错