http: refactor auth loop

This commit is contained in:
samm81 2025-09-13 21:29:34 +07:00 committed by Hugo
parent 4990cdf229
commit 81d8444810

View file

@ -259,8 +259,8 @@ async def request(
kwargs["ssl"] = ssl_context kwargs["ssl"] = ssl_context
headers = kwargs.pop("headers", {}) headers = kwargs.pop("headers", {})
num_401 = 0 response: aiohttp.ClientResponse | None = None
while num_401 < 2: for _attempt in range(2):
if auth: if auth:
headers["Authorization"] = auth.get_auth_header(method, url) headers["Authorization"] = auth.get_auth_header(method, url)
try: try:
@ -279,17 +279,24 @@ async def request(
raise TransientNetworkError(str(e)) from e raise TransientNetworkError(str(e)) from e
raise e from None raise e from None
if response is None:
raise RuntimeError("No HTTP response obtained")
if response.ok or not auth: if response.ok or not auth:
# we don't need to do the 401-loop if we don't do auth in the first place # we don't need to do the 401-loop if we don't do auth in the first place
break break
if response.status == 401: if response.status == 401:
num_401 += 1
auth.handle_401(response) auth.handle_401(response)
# retry once more after handling the 401 challenge
continue
else: else:
# some other error, will be handled later on # some other error, will be handled later on
break break
if response is None:
raise RuntimeError("No HTTP response obtained")
# See https://github.com/kennethreitz/requests/issues/2042 # See https://github.com/kennethreitz/requests/issues/2042
content_type = response.headers.get("Content-Type", "") content_type = response.headers.get("Content-Type", "")
if ( if (