Skip to content

Commit

Permalink
[PR #9367/b612127d backport][3.11] Speed up handling auth in urls (#9381
Browse files Browse the repository at this point in the history
)

Co-authored-by: J. Nick Koston <nick@koston.org>
  • Loading branch information
patchback[bot] and bdraco authored Oct 1, 2024
1 parent c95998e commit 9f8721a
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 8 deletions.
5 changes: 2 additions & 3 deletions aiohttp/client_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,9 +403,8 @@ def update_host(self, url: URL) -> None:
raise InvalidURL(url)

# basic auth info
username, password = url.user, url.password
if username or password:
self.auth = helpers.BasicAuth(username or "", password or "")
if url.raw_user or url.raw_password:
self.auth = helpers.BasicAuth(url.user or "", url.password or "")

def update_version(self, version: Union[http.HttpVersion, str]) -> None:
"""Convert request version to two elements tuple.
Expand Down
13 changes: 8 additions & 5 deletions aiohttp/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,9 @@ def from_url(cls, url: URL, *, encoding: str = "latin1") -> Optional["BasicAuth"
"""Create BasicAuth from url."""
if not isinstance(url, URL):
raise TypeError("url should be yarl.URL instance")
if url.user is None and url.password is None:
# Check raw_user and raw_password first as yarl is likely
# to already have these values parsed from the netloc in the cache.
if url.raw_user is None and url.raw_password is None:
return None
return cls(url.user or "", url.password or "", encoding=encoding)

Expand All @@ -174,11 +176,12 @@ def encode(self) -> str:


def strip_auth_from_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]:
auth = BasicAuth.from_url(url)
if auth is None:
"""Remove user and password from URL if present and return BasicAuth object."""
# Check raw_user and raw_password first as yarl is likely
# to already have these values parsed from the netloc in the cache.
if url.raw_user is None and url.raw_password is None:
return url, None
else:
return url.with_user(None), auth
return url.with_user(None), BasicAuth(url.user or "", url.password or "")


def netrc_from_env() -> Optional[netrc.netrc]:
Expand Down
6 changes: 6 additions & 0 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,12 @@ def test_basic_auth_no_user_from_url() -> None:
assert auth.password == "pass"


def test_basic_auth_no_auth_from_url() -> None:
url = URL("http://example.com")
auth = helpers.BasicAuth.from_url(url)
assert auth is None


def test_basic_auth_from_not_url() -> None:
with pytest.raises(TypeError):
helpers.BasicAuth.from_url("http://user:pass@example.com")
Expand Down

0 comments on commit 9f8721a

Please sign in to comment.