Skip to content

Commit

Permalink
[PR #9309/e4028333 backport][3.10] Fix building the URL in BaseReques…
Browse files Browse the repository at this point in the history
…t when the host contains a port or IPv6 address (#9318)

Co-authored-by: J. Nick Koston <nick@koston.org>
fixes #9307
  • Loading branch information
patchback[bot] authored Sep 27, 2024
1 parent d32d580 commit 8220ced
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGES/9309.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed assembling the :class:`~yarl.URL` for web requests when the host contains a non-default port or IPv6 address -- by :user:`bdraco`.
10 changes: 8 additions & 2 deletions aiohttp/web_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,10 @@ def host(self) -> str:
- overridden value by .clone(host=new_host) call.
- HOST HTTP header
- socket.getfqdn() value
For example, 'example.com' or 'localhost:8080'.
For historical reasons, the port number may be included.
"""
host = self._message.headers.get(hdrs.HOST)
if host is not None:
Expand All @@ -454,8 +458,10 @@ def remote(self) -> Optional[str]:

@reify
def url(self) -> URL:
url = URL.build(scheme=self.scheme, host=self.host)
return url.join(self._rel_url)
"""The full URL of the request."""
# authority is used here because it may include the port number
# and we want yarl to parse it correctly
return URL.build(scheme=self.scheme, authority=self.host).join(self._rel_url)

@reify
def path(self) -> str:
Expand Down
10 changes: 10 additions & 0 deletions tests/test_web_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,16 @@ def test_url_url() -> None:
assert URL("http://example.com/path") == req.url


def test_url_non_default_port() -> None:
req = make_mocked_request("GET", "/path", headers={"HOST": "example.com:8123"})
assert req.url == URL("http://example.com:8123/path")


def test_url_ipv6() -> None:
req = make_mocked_request("GET", "/path", headers={"HOST": "[::1]:8123"})
assert req.url == URL("http://[::1]:8123/path")


def test_clone() -> None:
req = make_mocked_request("GET", "/path")
req2 = req.clone()
Expand Down

0 comments on commit 8220ced

Please sign in to comment.