您的位置:首页 > 编程语言 > Python开发

Python retry的一个AOP实现 (Python中级)

2015-07-10 10:43 337 查看
def retry(condition, retry_times, interval=60, ignore_error=True):
"""
@condition: condition variable or func.
@retry_times: you know it means.
@interval: wait time before retrying
@param: ignore_error, retry if error happened.
"""
def wrap(f):
def wrapped_f(*args):
__retry_times = retry_times - 1
__interval = interval
__ignore_error = ignore_error
__does_error_happened = False
if not hasattr(f, '__call__'):
raise RetryException("func is not a callable.")
if type(__retry_times) != int:
raise RetryException("retry_times is not a number.")
if __retry_times < 0:
__retry_times = 0

def get_condition():
if __ignore_error and __does_error_happened:
return True
elif hasattr(condition, '__call__'):
return condition()
else:
return condition

while get_condition() and __retry_times >= 0:
print("Retry times remain -> ", __retry_times)
try:
f(*args)
__does_error_happened = False
except Exception as e:
print("##############################################################################")
print("                     >>>   Exception Happened   <<<                           ")
print(traceback.format_exc())
print("                     ^^^   Check What Happened  ^^^                           ")
print("##############################################################################")
__does_error_happened = True
if not ignore_error:
raise e
__retry_times -= 1
if get_condition():
print ("""
******************************************************************************
Condition fail, retry will be performed in next %ss
******************************************************************************
""" % interval)
time.sleep(__interval)
return wrapped_f
return wrap


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: