Skip to content

Commit ee36c33

Browse files
ngnpopefelixxm
authored andcommitted
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.
1 parent c77fbda commit ee36c33

File tree

1 file changed

+6
-14
lines changed

1 file changed

+6
-14
lines changed

django/http/request.py

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030

3131
RAISE_ERROR = object()
3232
host_validation_re = _lazy_re_compile(
33-
r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:[0-9]+)?$"
33+
r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9.:]+\])(?::([0-9]+))?$"
3434
)
3535

3636

@@ -698,19 +698,11 @@ def split_domain_port(host):
698698
Returned domain is lowercased. If the host is invalid, the domain will be
699699
empty.
700700
"""
701-
host = host.lower()
702-
703-
if not host_validation_re.match(host):
704-
return "", ""
705-
706-
if host[-1] == "]":
707-
# It's an IPv6 address without a port.
708-
return host, ""
709-
bits = host.rsplit(":", 1)
710-
domain, port = bits if len(bits) == 2 else (bits[0], "")
711-
# Remove a trailing dot (if present) from the domain.
712-
domain = domain.removesuffix(".")
713-
return domain, port
701+
if match := host_validation_re.fullmatch(host.lower()):
702+
domain, port = match.groups(default="")
703+
# Remove a trailing dot (if present) from the domain.
704+
return domain.removesuffix("."), port
705+
return "", ""
714706

715707

716708
def validate_host(host, allowed_hosts):

0 commit comments

Comments
 (0)