Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve performance of handling ports in the URL #1081

Merged
merged 9 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/1081.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved performance of handling ports -- by :user:.
24 changes: 14 additions & 10 deletions yarl/_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ def __str__(self):
val = self._val
if not val.path and self.is_absolute() and (val.query or val.fragment):
val = val._replace(path="/")
if (port := self._get_port()) is None:
if (port := self._port_not_default) is None:
# port normalization - using None for default ports to remove from rendering
# https://datatracker.ietf.org/doc/html/rfc3986.html#section-6.2.3
val = val._replace(
Expand Down Expand Up @@ -371,7 +371,7 @@ def is_default_port(self):
if self.explicit_port is None:
# A relative URL does not have an implicit port / default port
return self.port is not None
default = self._get_default_port()
default = self._default_port
if default is None:
return False
return self.port == default
Expand Down Expand Up @@ -421,17 +421,21 @@ def raw_authority(self):
"""
return self._val.netloc

def _get_default_port(self) -> Union[int, None]:
@cached_property
def _default_port(self) -> Union[int, None]:
"""Default port for the scheme or None if not known."""
scheme = self.scheme
if not scheme:
return None
return DEFAULT_PORTS.get(scheme)

def _get_port(self) -> Union[int, None]:
"""Port or None if default port"""
if self._get_default_port() == self.port:
@cached_property
def _port_not_default(self) -> Union[int, None]:
"""The port part of URL normalized to None if its the default port."""
port = self.port
if self._default_port == port:
return None
return self.port
return port

@cached_property
def authority(self):
Expand Down Expand Up @@ -520,9 +524,9 @@ def port(self):
scheme without default port substitution.

"""
return self._val.port or self._get_default_port()
return self.explicit_port or self._default_port

@property
@cached_property
def explicit_port(self):
"""Port part of URL, without scheme-based fallback.

Expand Down Expand Up @@ -1142,7 +1146,7 @@ def human_repr(self):
user,
password,
host,
self._val.port,
self.explicit_port,
encode_host=False,
),
path,
Expand Down
Loading