Skip to content

Commit 695336f

Browse files
Use compiled regexes
1 parent b5d95f3 commit 695336f

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

stac_fastapi/api/stac_fastapi/api/middleware.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Api middleware."""
22

3+
import contextlib
34
import re
45
import typing
56
from http.client import HTTP_PORT, HTTPS_PORT
@@ -44,6 +45,10 @@ def __init__(
4445
)
4546

4647

48+
_PROTO_HEADER_REGEX = re.compile(r"proto=(?P<proto>http(s)?)")
49+
_HOST_HEADER_REGEX = re.compile(r"host=(?P<host>[\w.-]+)(:(?P<port>\d{1,5}))?")
50+
51+
4752
class ProxyHeaderMiddleware:
4853
"""Account for forwarding headers when deriving base URL.
4954
@@ -92,25 +97,20 @@ def _get_forwarded_url_parts(self, scope: Scope) -> Tuple[str]:
9297

9398
if forwarded := self._get_header_value_by_name(scope, "forwarded"):
9499
for proxy in forwarded.split(","):
95-
if (proto_expr := re.search(r"proto=(?P<proto>http(s)?)", proxy)) and (
96-
host_expr := re.search(
97-
r"host=(?P<host>[\w.-]+)(:(?P<port>\d{1,5}))?", proxy
98-
)
100+
if (proto_expr := _PROTO_HEADER_REGEX.search(proxy)) and (
101+
host_expr := _HOST_HEADER_REGEX.search(proxy)
99102
):
100-
proto = proto_expr.groupdict()["proto"]
101-
domain = host_expr.groupdict()["host"]
102-
port_str = host_expr.groupdict().get("port", None)
103+
proto = proto_expr.group("proto")
104+
domain = host_expr.group("host")
105+
port_str = host_expr.group("port") # None if not present in the match
103106

104107
else:
105108
domain = self._get_header_value_by_name(scope, "x-forwarded-host", domain)
106109
proto = self._get_header_value_by_name(scope, "x-forwarded-proto", proto)
107110
port_str = self._get_header_value_by_name(scope, "x-forwarded-port", port)
108111

109-
try:
112+
with contextlib.suppress(ValueError): # ignore ports that are not valid integers
110113
port = int(port_str) if port_str is not None else port
111-
except ValueError:
112-
# ignore ports that are not valid integers
113-
pass
114114

115115
return (proto, domain, port)
116116

0 commit comments

Comments
 (0)