11import os
2+ from time import sleep
3+ from requests .models import Response
24from oauthlib .oauth2 import BackendApplicationClient , TokenExpiredError
35from requests_oauthlib import OAuth2Session
46from nypl_py_utils .functions .log_helper import create_log
@@ -11,7 +13,7 @@ class Oauth2ApiClient:
1113 """
1214
1315 def __init__ (self , client_id = None , client_secret = None , base_url = None ,
14- token_url = None ):
16+ token_url = None , with_retries = False ):
1517 self .client_id = client_id \
1618 or os .environ .get ('NYPL_API_CLIENT_ID' , None )
1719 self .client_secret = client_secret \
@@ -25,11 +27,29 @@ def __init__(self, client_id=None, client_secret=None, base_url=None,
2527
2628 self .logger = create_log ('oauth2_api_client' )
2729
30+ self .with_retries = with_retries
31+
2832 def get (self , request_path , ** kwargs ):
2933 """
3034 Issue an HTTP GET on the given request_path
3135 """
32- return self ._do_http_method ('GET' , request_path , ** kwargs )
36+ resp = self ._do_http_method ('GET' , request_path , ** kwargs )
37+ if resp .json () is None and self .with_retries is True :
38+ retries = \
39+ kwargs .get ('retries' , 0 ) + 1
40+ if retries < 3 :
41+ self .logger .warning (
42+ f'Retrying get request due to empty response from\
43+ Oauth2 Client. Retry #{ retries } ' )
44+ sleep (pow (2 , retries - 1 ))
45+ kwargs ['retries' ] = retries
46+ resp = self .get (request_path , ** kwargs )
47+ else :
48+ resp = Response ()
49+ resp .message = 'Oauth2 Client: Request failed after 3 \
50+ empty responses received from Oauth2 Client'
51+ resp .status_code = 500
52+ return resp
3353
3454 def post (self , request_path , json , ** kwargs ):
3555 """
@@ -79,7 +99,7 @@ def _do_http_method(self, method, request_path, **kwargs):
7999 from None
80100
81101 self ._generate_access_token ()
82- return self ._do_http_method (method , request_path , ** kwargs )
102+ return self ._do_http_method (method , request_path , ** kwargs ). json ()
83103
84104 def _create_oauth_client (self ):
85105 """
0 commit comments