1
0
mirror of https://github.com/django/django.git synced 2025-03-31 19:46:42 +00:00

Simplified django.http.request.split_domain_port().

Use the capture groups from the regular expression that has already been
matched to avoid resplitting and the need to special case for IPv6.
This commit is contained in:
Nick Pope 2023-07-27 11:27:46 +01:00 committed by Mariusz Felisiak
parent c77fbda7ce
commit ee36c332b2

View File

@ -30,7 +30,7 @@ from django.utils.regex_helper import _lazy_re_compile
RAISE_ERROR = object() RAISE_ERROR = object()
host_validation_re = _lazy_re_compile( host_validation_re = _lazy_re_compile(
r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:[0-9]+)?$" r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9.:]+\])(?::([0-9]+))?$"
) )
@ -698,19 +698,11 @@ def split_domain_port(host):
Returned domain is lowercased. If the host is invalid, the domain will be Returned domain is lowercased. If the host is invalid, the domain will be
empty. empty.
""" """
host = host.lower() if match := host_validation_re.fullmatch(host.lower()):
domain, port = match.groups(default="")
if not host_validation_re.match(host): # Remove a trailing dot (if present) from the domain.
return "", "" return domain.removesuffix("."), port
return "", ""
if host[-1] == "]":
# It's an IPv6 address without a port.
return host, ""
bits = host.rsplit(":", 1)
domain, port = bits if len(bits) == 2 else (bits[0], "")
# Remove a trailing dot (if present) from the domain.
domain = domain.removesuffix(".")
return domain, port
def validate_host(host, allowed_hosts): def validate_host(host, allowed_hosts):