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
相关文章推荐
- python如何保持登陆状态的简单现实
- 层次聚类算法的python实现
- Python使用时间戳
- Python中获取异常(Exception)信息
- python中sorted()函数的应用
- 【Python】Windows版本的Python开发环境的配置,Helloworld,Python中文问题,输入输出、条件、循环、数组、类
- Python Xpath与Regex的区别
- Python什么是二次开发的意义?python在.net项目采用
- 【Python】python环境的搭建之windows篇
- python基础之数据类型语句
- Python笔记:random模块常用函数
- Python中的一些陷阱与技巧小结
- python beautifulsoup抓取京东商品名称和价格
- Python实现检测代理IP是否可以翻墙
- Scikit-Learn:开源的机器学习Python模块
- python文件操作
- ADT in python DEMO
- python的绿色版本
- rebot的使用
- Robot Framework安装指南