码迷,mamicode.com
首页 > 其他好文 > 详细

实现一个重试装饰器

时间:2018-11-15 01:27:45      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:error   lam   ret   obj   for   actually   yield   stop   iter   

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

实现一个重试装饰器

标签:error   lam   ret   obj   for   actually   yield   stop   iter   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!