Skip to content

Commit

Permalink
Retries for Access Token Request (#19)
Browse files Browse the repository at this point in the history
* Added retries for access token
  • Loading branch information
muhammadali286 authored Jun 25, 2024
1 parent 21da1ad commit 810eb07
Showing 1 changed file with 27 additions and 9 deletions.
36 changes: 27 additions & 9 deletions credentials/apps/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import datetime
import hashlib
import logging
import time
from requests.models import Response

from django.conf import settings
from django.contrib.auth.models import AbstractUser
Expand Down Expand Up @@ -192,15 +194,31 @@ def access_token(self):

if not access_token:
url = f'{self.oauth2_provider_url}/access_token'
access_token, expiration_datetime = EdxRestApiClient.get_oauth_access_token(
url,
self.oauth2_client_id,
self.oauth2_client_secret,
token_type='jwt'
)

expires = (expiration_datetime - datetime.datetime.utcnow()).seconds
cache.set(key, access_token, expires)
retries = [15, 30, 45] # Retry delays in seconds
attempt = 0

while attempt < len(retries) + 1:
try:
log.info(f'Feching access token for URL: {url}')
access_token, expiration_datetime = EdxRestApiClient.get_oauth_access_token(
url,
self.oauth2_client_id,
self.oauth2_client_secret,
token_type='jwt'
)
expires = (expiration_datetime - datetime.datetime.utcnow()).seconds
cache.set(key, access_token, expires)
return access_token
except Exception as e:
log.info(f'Getting exception wile getting token {e}')
if isinstance(e.response, Response) and e.response.status_code == 403:
attempt += 1
if attempt > len(retries):
raise e

seconds = retries[attempt - 1]
log.info(f'Retrying attempt no: {attempt} for access token request after seconds: {seconds} because of exceptoin {e}')
time.sleep(seconds)

return access_token

Expand Down

0 comments on commit 810eb07

Please sign in to comment.