Skip to content

Instantly share code, notes, and snippets.

@arpithkp
Created July 6, 2015 15:02
Show Gist options
  • Save arpithkp/029a99bbadc019a6c963 to your computer and use it in GitHub Desktop.
Save arpithkp/029a99bbadc019a6c963 to your computer and use it in GitHub Desktop.
def retry(func, timeout=DEFAULT_TIMEOUT, retry_delay=DEFAULT_SLEEP, backoff=DEFAULT_BACKCOFF,
retry_exceptions=(RateLimit, socket.error, socket.gaierror, httplib.NotConnected,
httplib.ImproperConnectionState), *args, **kwargs):
"""
Retry decorator helps to handle common exception.
:param timeout: Default timeout
"""
timeout = timeout
bsleep = retry_delay
backoff = backoff
end = datetime.now() + timedelta(seconds=timeout)
exc_info = None
while datetime.now() < end:
try:
result = func(*args, **kwargs)
return result
except Exception, exc:
if any((isinstance(exc, exc_type) for exc_type in retry_exceptions)):
if isinstance(RateLimit, exc):
time.sleep(exc.retry_after)
end = datetime.now() + timedelta(seconds=exc.retry_after + timeout)
else:
exc_info = sys.exc_info()
time.sleep(bsleep)
bsleep += backoff
if exc_info:
raise exc_info[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment