Skip to content

Instantly share code, notes, and snippets.

@vsudilov
Created May 18, 2015 18:59
Show Gist options
  • Save vsudilov/ff5598d07de1fe9d412f to your computer and use it in GitHub Desktop.
Save vsudilov/ff5598d07de1fe9d412f to your computer and use it in GitHub Desktop.
python-retry decorator
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