Created
May 18, 2015 18:59
-
-
Save vsudilov/ff5598d07de1fe9d412f to your computer and use it in GitHub Desktop.
python-retry decorator
This file contains hidden or 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
def with_retry_connections(max_tries=3, sleep=0.05): | |
""" | |
Decorator that wraps an entire function in a try/except clause. On | |
requests.exceptions.ConnectionError, will re-run the function code | |
until success or max_tries is reached. | |
:param max_tries: maximum number of attempts before giving up | |
:param sleep: time to sleep between tries, or None | |
""" | |
def decorator(f): | |
def f_retry(*args, **kwargs): | |
tries = 0 | |
while 1: | |
try: | |
return f(*args, **kwargs) | |
except ConnectionError: | |
tries += 1 | |
if tries >= max_tries: | |
raise | |
if sleep: | |
time.sleep(sleep) | |
return f_retry | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment