23
23
class Route :
24
24
"""Route definition for different paths, see `adafruit_httpserver.server.Server.route`."""
25
25
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
+
26
44
def __init__ (
27
45
self ,
28
46
path : str = "" ,
@@ -33,22 +51,15 @@ def __init__(
33
51
) -> None :
34
52
self ._validate_path (path , append_slash )
35
53
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
- )
47
54
self .path = path
48
55
self .methods = (
49
56
set (methods ) if isinstance (methods , (set , list , tuple )) else set ([methods ])
50
57
)
51
58
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 ))
52
63
53
64
@staticmethod
54
65
def _validate_path (path : str , append_slash : bool ) -> None :
0 commit comments