20
20
from .methods import GET
21
21
22
22
23
- class _Route :
23
+ class Route :
24
24
"""Route definition for different paths, see `adafruit_httpserver.server.Server.route`."""
25
25
26
26
def __init__ (
27
27
self ,
28
28
path : str = "" ,
29
29
methods : Union [str , Set [str ]] = GET ,
30
+ handler : Callable = None ,
31
+ * ,
30
32
append_slash : bool = False ,
31
33
) -> None :
32
- self ._validate_path (path )
34
+ self ._validate_path (path , append_slash )
33
35
34
36
self .parameters_names = [
35
37
name [1 :- 1 ] for name in re .compile (r"/[^<>]*/?" ).split (path ) if name != ""
36
38
]
37
39
self .path = re .sub (r"<\w+>" , r"([^/]+)" , path ).replace ("...." , r".+" ).replace (
38
40
"..." , r"[^/]+"
39
41
) + ("/?" if append_slash else "" )
40
- self .methods = methods if isinstance (methods , set ) else {methods }
42
+ self .methods = set (methods ) if isinstance (methods , (set , list )) else set ([methods ])
43
+
44
+ self .handler = handler
41
45
42
46
@staticmethod
43
- def _validate_path (path : str ) -> None :
47
+ def _validate_path (path : str , append_slash : bool ) -> None :
44
48
if not path .startswith ("/" ):
45
49
raise ValueError ("Path must start with a slash." )
46
50
47
51
if "<>" in path :
48
52
raise ValueError ("All URL parameters must be named." )
49
53
50
- def match (self , other : "_Route" ) -> Tuple [bool , List [str ]]:
54
+ if path .endswith ("/" ) and append_slash :
55
+ raise ValueError ("Cannot use append_slash=True when path ends with /" )
56
+
57
+ def match (self , other : "Route" ) -> Tuple [bool , List [str ]]:
51
58
"""
52
59
Checks if the route matches the other route.
53
60
@@ -59,34 +66,34 @@ def match(self, other: "_Route") -> Tuple[bool, List[str]]:
59
66
60
67
Examples::
61
68
62
- route = _Route ("/example", GET, True)
69
+ route = Route ("/example", GET, True)
63
70
64
- other1a = _Route ("/example", GET)
65
- other1b = _Route ("/example/", GET)
71
+ other1a = Route ("/example", GET)
72
+ other1b = Route ("/example/", GET)
66
73
route.matches(other1a) # True, []
67
74
route.matches(other1b) # True, []
68
75
69
- other2 = _Route ("/other-example", GET)
76
+ other2 = Route ("/other-example", GET)
70
77
route.matches(other2) # False, []
71
78
72
79
...
73
80
74
- route = _Route ("/example/<parameter>", GET)
81
+ route = Route ("/example/<parameter>", GET)
75
82
76
- other1 = _Route ("/example/123", GET)
83
+ other1 = Route ("/example/123", GET)
77
84
route.matches(other1) # True, ["123"]
78
85
79
- other2 = _Route ("/other-example", GET)
86
+ other2 = Route ("/other-example", GET)
80
87
route.matches(other2) # False, []
81
88
82
89
...
83
90
84
- route1 = _Route ("/example/.../something", GET)
85
- other1 = _Route ("/example/123/something", GET)
91
+ route1 = Route ("/example/.../something", GET)
92
+ other1 = Route ("/example/123/something", GET)
86
93
route1.matches(other1) # True, []
87
94
88
- route2 = _Route ("/example/..../something", GET)
89
- other2 = _Route ("/example/123/456/something", GET)
95
+ route2 = Route ("/example/..../something", GET)
96
+ other2 = Route ("/example/123/456/something", GET)
90
97
route2.matches(other2) # True, []
91
98
"""
92
99
@@ -103,23 +110,20 @@ def __repr__(self) -> str:
103
110
path = repr (self .path )
104
111
methods = repr (self .methods )
105
112
106
- return f"_Route (path={ path } , methods={ methods } )"
113
+ return f"Route (path={ path } , methods={ methods } )"
107
114
108
115
109
116
class _Routes :
110
117
"""A collection of routes and their corresponding handlers."""
111
118
112
119
def __init__ (self ) -> None :
113
- self ._routes : List [_Route ] = []
114
- self ._handlers : List [Callable ] = []
120
+ self ._routes : List [Route ] = []
115
121
116
- def add (self , route : _Route , handler : Callable ):
122
+ def add (self , route : Route ):
117
123
"""Adds a route and its handler to the collection."""
118
-
119
124
self ._routes .append (route )
120
- self ._handlers .append (handler )
121
125
122
- def find_handler (self , route : _Route ) -> Union [Callable ["..." , "Response" ], None ]:
126
+ def find_handler (self , route : Route ) -> Union [Callable ["..." , "Response" ], None ]:
123
127
"""
124
128
Finds a handler for a given route.
125
129
@@ -146,7 +150,7 @@ def route_func(request, my_parameter):
146
150
if not found_route :
147
151
return None
148
152
149
- handler = self . _handlers [ self . _routes . index ( _route )]
153
+ handler = _route . handler
150
154
151
155
keyword_parameters = dict (zip (_route .parameters_names , parameters_values ))
152
156
0 commit comments