From 810eb072f2a4ef0fe6ada9c4a58b4ec0f5299869 Mon Sep 17 00:00:00 2001 From: Muhammad Ali Date: Mon, 24 Jun 2024 23:17:46 -0700 Subject: [PATCH] Retries for Access Token Request (#19) * Added retries for access token --- credentials/apps/core/models.py | 36 ++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/credentials/apps/core/models.py b/credentials/apps/core/models.py index 2596e31b7..82656d50f 100644 --- a/credentials/apps/core/models.py +++ b/credentials/apps/core/models.py @@ -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 @@ -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