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

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

  

posted @ 2015-07-10 10:43  velly.zhou  阅读(538)  评论(1编辑  收藏  举报