Skip to content

Commit 7be1e70

Browse files
committed
Refactor of parsing path_pattern
1 parent b6664cf commit 7be1e70

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

adafruit_httpserver/route.py

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,24 @@
2323
class Route:
2424
"""Route definition for different paths, see `adafruit_httpserver.server.Server.route`."""
2525

26+
@staticmethod
27+
def _prepare_path_pattern(path: str, append_slash: bool) -> str:
28+
# Escape all dots
29+
path = re.sub(r"\.", r"\\.", path)
30+
31+
# Replace url parameters with regex groups
32+
path = re.sub(r"<\w+>", r"([^/]+)", path)
33+
34+
# Replace wildcards with corresponding regex
35+
path = path.replace(r"\.\.\.\.", r".+").replace(r"\.\.\.", r"[^/]+")
36+
37+
# Add optional slash at the end if append_slash is True
38+
if append_slash:
39+
path += r"/?"
40+
41+
# Add start and end of string anchors
42+
return f"^{path}$"
43+
2644
def __init__(
2745
self,
2846
path: str = "",
@@ -33,22 +51,15 @@ def __init__(
3351
) -> None:
3452
self._validate_path(path, append_slash)
3553

36-
self.parameters_names = [
37-
name[1:-1] for name in re.compile(r"/[^<>]*/?").split(path) if name != ""
38-
]
39-
self.path_pattern = re.compile(
40-
r"^"
41-
+ re.sub(r"<\w+>", r"([^/]+)", path)
42-
.replace(r"....", r".+")
43-
.replace(r"...", r"[^/]+")
44-
+ (r"/?" if append_slash else r"")
45-
+ r"$"
46-
)
4754
self.path = path
4855
self.methods = (
4956
set(methods) if isinstance(methods, (set, list, tuple)) else set([methods])
5057
)
5158
self.handler = handler
59+
self.parameters_names = [
60+
name[1:-1] for name in re.compile(r"/[^<>]*/?").split(path) if name != ""
61+
]
62+
self.path_pattern = re.compile(self._prepare_path_pattern(path, append_slash))
5263

5364
@staticmethod
5465
def _validate_path(path: str, append_slash: bool) -> None:

0 commit comments

Comments
 (0)