-
Notifications
You must be signed in to change notification settings - Fork 109
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #964 from glensc/logical-decorator-retry
Refactor: Add retry decorator
- Loading branch information
Showing
4 changed files
with
81 additions
and
21 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
from functools import wraps | ||
from time import sleep | ||
|
||
from plexapi.exceptions import BadRequest | ||
from requests import ReadTimeout, RequestException | ||
from trakt.errors import TraktInternalException | ||
|
||
from plextraktsync.logging import logger | ||
|
||
|
||
def retry(retries=5): | ||
""" | ||
retry a call retries times | ||
:param retries: number of retries | ||
:return: | ||
""" | ||
|
||
def decorator(fn): | ||
@wraps(fn) | ||
def wrapper(*args, **kwargs): | ||
count = 0 | ||
while True: | ||
try: | ||
return fn(*args, **kwargs) | ||
except ( | ||
BadRequest, | ||
ReadTimeout, | ||
RequestException, | ||
TraktInternalException, | ||
) as e: | ||
if count == retries: | ||
logger.error(f"Error: {e}") | ||
logger.error( | ||
"API didn't respond properly, script will abort now. Please try again later." | ||
) | ||
logger.error( | ||
f"Last call: {fn.__module__}.{fn.__name__}({args[1:]}, {kwargs})" | ||
) | ||
exit(1) | ||
|
||
seconds = 1 + count | ||
count += 1 | ||
logger.warning( | ||
f"{e} for {fn.__module__}.{fn.__name__}(), retrying after {seconds} seconds (try: {count}/{retries})" | ||
) | ||
sleep(seconds) | ||
|
||
return wrapper | ||
|
||
return decorator |
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
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