Skip to content
This repository was archived by the owner on May 5, 2025. It is now read-only.

Commit 8098bb1

Browse files
authored
Add auto_refresh support to _apply_credentials method (#122)
1 parent f19404c commit 8098bb1

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

pancloud/httpclient.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,10 @@ def __init__(self, **kwargs):
9898

9999
if self.credentials:
100100
self._apply_credentials(
101-
self.credentials, self.session.headers)
101+
auto_refresh=self.auto_refresh,
102+
credentials=self.credentials,
103+
headers=self.session.headers
104+
)
102105

103106
def __repr__(self):
104107
for k in self.kwargs.get('headers', {}):
@@ -118,22 +121,26 @@ def __repr__(self):
118121
)
119122

120123
@staticmethod
121-
def _apply_credentials(credentials, headers):
124+
def _apply_credentials(auto_refresh=True, credentials=None,
125+
headers=None):
122126
"""Update Authorization header.
123127
124128
Update request headers with latest `access_token`. Perform token
125129
`refresh` if token is ``None``.
126130
127131
Args:
132+
auto_refresh (bool): Perform token refresh if access_token is ``None`` or expired. Defaults to ``True``.
128133
credentials (class): Read-only credentials.
129134
headers (class): Requests `CaseInsensitiveDict`.
130135
131136
"""
132137
token = credentials.get_credentials().access_token
133-
if token is None:
134-
token = credentials.refresh(access_token=None, timeout=10)
135-
elif credentials.jwt_is_expired():
136-
token = credentials.refresh(timeout=10)
138+
if auto_refresh is True:
139+
if token is None:
140+
token = credentials.refresh(
141+
access_token=None, timeout=10)
142+
elif credentials.jwt_is_expired():
143+
token = credentials.refresh(timeout=10)
137144
headers.update(
138145
{'Authorization': "Bearer {}".format(token)}
139146
)
@@ -263,12 +270,15 @@ def request(self, **kwargs):
263270
r = self._send_request(
264271
enforce_json, method, raise_for_status, url, **k
265272
)
273+
# TODO remove the following if statement
266274
if r.status_code == 401:
267275
if credentials and auto_refresh:
268276
token = credentials.get_credentials().access_token
269277
credentials.refresh(access_token=token, timeout=10)
270278
self._apply_credentials(
271-
credentials, headers or self.session.headers
279+
auto_refresh=auto_refresh,
280+
credentials=credentials,
281+
headers=headers or self.session.headers
272282
)
273283
if auto_retry:
274284
r = self._send_request(

0 commit comments

Comments
 (0)