Skip to content

Instantly share code, notes, and snippets.

@windard
Created December 27, 2019 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save windard/0847d44af575cc44be419dbab4602241 to your computer and use it in GitHub Desktop.
Save windard/0847d44af575cc44be419dbab4602241 to your computer and use it in GitHub Desktop.
retry_with_times
# coding=utf-8
def catch_retry(times):
def inner(func):
def wrapper(*args, **kwargs):
for _ in range(times):
try:
return func(*args, **kwargs)
except Exception as e:
print 'exception', e
return None
return wrapper
return inner
def call_with_retry(retry_count):
"""
retry three times, total four times
:param retry_count:
:return:
"""
def inner(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
if retry_count <= 0:
raise
print 'exception', e
return call_with_retry(retry_count-1)(func)(*args, **kwargs)
return wrapper
return inner
def retry_func_wrapper(retry_times):
def inner(func):
def wrapper(*args, **kwargs):
def retry(times):
try:
return func(*args, **kwargs)
except Exception as e:
if times <= 0:
raise
print 'exception', e
return retry(times - 1)
return retry(retry_times)
return wrapper
return inner
@catch_retry(3)
def div(a, b):
return a / b
@call_with_retry(3)
def ddiv(a, b):
return a / b
@retry_func_wrapper(3)
def divv(a, b):
return a / b
if __name__ == '__main__':
# div(1, 0)
# ddiv(1, 0)
print divv(1, 0)
@windard
Copy link
Author

windard commented Feb 18, 2021

def retry(times=3):
    def inner(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            count = 0
            while count < times:
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    print("occur error:%r" % e)
                    count += 1
            raise
        return wrapper

    return inner

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment