Created
February 13, 2019 21:42
-
-
Save gekitsuu/54589628f3f77e95afeb5e1e4dcde119 to your computer and use it in GitHub Desktop.
Decorator to retry on exceptions
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
import time | |
import logging | |
from functools import wraps | |
def retry_errors(exceptions, timeout=300, wait_time=10): | |
"""Catch exceptions and retry until the timeout is reached. | |
exceptions: An Exception object or tuple of exception objects. | |
timeout: Integer, defaults to 300 seconds. Time to attempt call before failing. | |
wait_time: Integer, defaults to 10 seconds. Time to wait between retries. | |
""" | |
def error_decorator(func): | |
start_time = int(time.time()) | |
@wraps(func) | |
def func_wrapper(*args, **kwargs): | |
current_time = start_time | |
while True: | |
current_time = int(time.time()) | |
try: | |
func(*args, **kwargs) | |
except exceptions as error: | |
logging.info("Exception raised, waiting {0} seconds to retry".format(wait_time)) | |
time.sleep(wait_time) | |
if current_time - start_time < timeout: | |
continue | |
else: | |
raise error | |
break | |
return func_wrapper | |
return error_decorator | |
@retry_errors(IndexError, timeout=30) | |
def foo(bar, baz): | |
bar + baz | |
raise IndexError | |
if __name__ == "__main__": | |
foo(1, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment