Created
December 27, 2019 03:44
-
-
Save windard/0847d44af575cc44be419dbab4602241 to your computer and use it in GitHub Desktop.
retry_with_times
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
Author
windard
commented
Feb 18, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment