Skip to content

Commit

Permalink
Add a docstring to retry_api_call and implement Client.retry
Browse files Browse the repository at this point in the history
  • Loading branch information
sHermanGriffiths committed May 6, 2024
1 parent 04f94bb commit 4490f3b
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions n2y/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,10 +299,15 @@ def load_yaml(data):


def retry_api_call(api_call):
"""
Retry an API call if it fails due to a rate limit or server error. Can only be used to
decorate methods of the `Client` class.
"""
max_api_retries = 4

@functools.wraps(api_call)
def wrapper(*args, retry_count=0, **kwargs):
client = args[0]
assert "retry_count" not in kwargs, "retry_count is a reserved keyword"
try:
return api_call(*args, **kwargs)
Expand All @@ -312,10 +317,9 @@ def wrapper(*args, retry_count=0, **kwargs):
raise err
elif retry_count < max_api_retries:
retry_count += 1
log = args[0].logger if args and hasattr(args[0], "logger") else logger
if "retry-after" in err.headers:
if client.retry and "retry-after" in err.headers:
retry_after = float(err.headers["retry-after"])
log.info(
client.logger.info(
"This API call has been rate limited and "
"will be retried in %f seconds. Attempt %d of %d.",
retry_after,
Expand All @@ -324,7 +328,7 @@ def wrapper(*args, retry_count=0, **kwargs):
)
else:
retry_after = 2
log.info(
client.logger.info(
"This API call failed and "
"will be retried in %f seconds. Attempt %d of %d.",
retry_after,
Expand Down

0 comments on commit 4490f3b

Please sign in to comment.