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
79class Oauth2ApiClient :
810 """
911 Client for interacting with an Oauth2 authenticated API such as NYPL's
10- Platform API endpoints
12+ Platform API endpoints. Note with_retries is a boolean flag which
13+ determines if empty get requests will be retried 3 times or until
14+ they are successful. This is to address a known issue with the Sierra
15+ API where empty responses are returned intermittently.
1116 """
1217
1318 def __init__ (self , client_id = None , client_secret = None , base_url = None ,
14- token_url = None ):
19+ token_url = None , with_retries = False ):
1520 self .client_id = client_id \
1621 or os .environ .get ('NYPL_API_CLIENT_ID' , None )
1722 self .client_secret = client_secret \
@@ -25,11 +30,30 @@ def __init__(self, client_id=None, client_secret=None, base_url=None,
2530
2631 self .logger = create_log ('oauth2_api_client' )
2732
33+ self .with_retries = with_retries
34+
2835 def get (self , request_path , ** kwargs ):
2936 """
3037 Issue an HTTP GET on the given request_path
3138 """
32- return self ._do_http_method ('GET' , request_path , ** kwargs )
39+ resp = self ._do_http_method ('GET' , request_path , ** kwargs )
40+ if resp .json () is None and self .with_retries is True :
41+ retries = \
42+ kwargs .get ('retries' , 0 ) + 1
43+ if retries < 3 :
44+ self .logger .warning (
45+ f'Retrying get request due to empty response from\
46+ Oauth2 Client using path: { request_path } . \
47+ Retry #{ retries } ' )
48+ sleep (pow (2 , retries - 1 ))
49+ kwargs ['retries' ] = retries
50+ resp = self .get (request_path , ** kwargs )
51+ else :
52+ resp = Response ()
53+ resp .message = 'Oauth2 Client: Request failed after 3 \
54+ empty responses received from Oauth2 Client'
55+ resp .status_code = 500
56+ return resp
3357
3458 def post (self , request_path , json , ** kwargs ):
3559 """
@@ -79,7 +103,7 @@ def _do_http_method(self, method, request_path, **kwargs):
79103 from None
80104
81105 self ._generate_access_token ()
82- return self ._do_http_method (method , request_path , ** kwargs )
106+ return self ._do_http_method (method , request_path , ** kwargs ). json ()
83107
84108 def _create_oauth_client (self ):
85109 """
0 commit comments