@@ -22,11 +22,12 @@ class _HTTPRoute:
22
22
23
23
def __init__ (self , path : str = "" , method : HTTPMethod = HTTPMethod .GET ) -> None :
24
24
25
- contains_regex = re .search (r"<\w*>" , path )
25
+ contains_regex = re .search (r"<\w*>" , path ) is not None
26
26
27
27
self .path = path if not contains_regex else re .sub (r"<\w*>" , r"([^/]*)" , path )
28
28
self .method = method
29
29
self ._contains_regex = contains_regex
30
+ self ._last_match_groups : Union [List [str ], None ] = None
30
31
31
32
def matches (self , other : "_HTTPRoute" ) -> bool :
32
33
"""
@@ -35,11 +36,27 @@ def matches(self, other: "_HTTPRoute") -> bool:
35
36
If the route contains parameters, it will check if the ``other`` route contains values for
36
37
them.
37
38
"""
39
+ if self .method != other .method :
40
+ return False
38
41
39
- if self ._contains_regex :
40
- return re . match ( self .path , other . path ) and self . method == other .method
42
+ if not self ._contains_regex :
43
+ return self .path == other .path
41
44
42
- return self .method == other .method and self .path == other .path
45
+ regex_match = re .match (self .path , other .path )
46
+ if regex_match is None :
47
+ return False
48
+
49
+ self ._last_match_groups = regex_match .groups ()
50
+ return True
51
+
52
+ def last_match_groups (self ) -> Union [List [str ], None ]:
53
+ """
54
+ Returns the last match groups from the last call to `matches`.
55
+
56
+ Useful for getting the values of the parameters from the route, without the need to call
57
+ `re.match` again.
58
+ """
59
+ return self ._last_match_groups
43
60
44
61
def __repr__ (self ) -> str :
45
62
return f"HTTPRoute(path={ repr (self .path )} , method={ repr (self .method )} )"
@@ -80,7 +97,7 @@ def route_func(request, my_parameter):
80
97
return None
81
98
82
99
handler = self ._handlers [self ._routes .index (matched_route )]
83
- args = re . match ( matched_route .path , route . path ). groups ()
100
+ args = matched_route .last_match_groups () or []
84
101
85
102
def wrapper (request ):
86
103
return handler (request , * args )
0 commit comments