Skip to content

Commit

Permalink
Merge pull request #14 from GermanoGuerrini/refreshed_token
Browse files Browse the repository at this point in the history
Fixed token renewal on forbidden responses
  • Loading branch information
ricardo-correa authored Sep 20, 2022
2 parents f9b66fd + 4abd866 commit 7d96faa
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions hda/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,9 @@ def is_token_expired():

return self._token

def invalidate_token(self):
self._token_creation_time = None

def get_token(self):
session = requests.Session()
session.auth = (self.user, self.password)
Expand All @@ -337,9 +340,12 @@ def session(self):
session = requests.Session()
session.mount("ftp://", FTPAdapter(self))
self._session = session
self._attach_auth()
return self._session

def _attach_auth(self):
self._session.headers = {"Authorization": self.token}
self.debug("Token is %s", self.token)
return self._session

def info(self, *args, **kwargs):
if self.info_callback:
Expand All @@ -366,7 +372,7 @@ def debug(self, *args, **kwargs):
self.logger.debug(*args, **kwargs)

def robust(self, call):
def retriable(code, reason):
def retriable(code):

if code in [
requests.codes.internal_server_error,
Expand All @@ -375,6 +381,7 @@ def retriable(code, reason):
requests.codes.gateway_timeout,
requests.codes.too_many_requests,
requests.codes.request_timeout,
requests.codes.forbidden,
]:
return True

Expand All @@ -395,12 +402,13 @@ def wrapped(*args, **kwargs):
)

if r is not None:
if not retriable(r.status_code, r.reason):
if not retriable(r.status_code):
return r

if r.status_code == requests.codes.forbidden:
# Try to renew the token next time
self._token_creation_time = None
self.debug("Trying to renew token")
self.invalidate_token()
self._attach_auth()

self.warning(
"Recovering from HTTP error [%s %s], attemps %s of %s",
Expand Down Expand Up @@ -443,8 +451,10 @@ def get(self, *args):

if self.debug:
self.session # Force login

full = self.full_url(*args)
self.debug("===> GET %s", full)

r = self.robust(self.session.get)(full, timeout=self.timeout)
r.raise_for_status()
result = r.json()
Expand Down

0 comments on commit 7d96faa

Please sign in to comment.