Skip to content

Commit 8ee162d

Browse files
committed
Changed Route class to public
1 parent 8165933 commit 8ee162d

File tree

3 files changed

+31
-31
lines changed

3 files changed

+31
-31
lines changed

adafruit_httpserver/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
JSONResponse,
6060
Redirect,
6161
)
62+
from .route import Route
6263
from .server import Server
6364
from .status import (
6465
Status,

adafruit_httpserver/route.py

Lines changed: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -20,34 +20,41 @@
2020
from .methods import GET
2121

2222

23-
class _Route:
23+
class Route:
2424
"""Route definition for different paths, see `adafruit_httpserver.server.Server.route`."""
2525

2626
def __init__(
2727
self,
2828
path: str = "",
2929
methods: Union[str, Set[str]] = GET,
30+
handler: Callable = None,
31+
*,
3032
append_slash: bool = False,
3133
) -> None:
32-
self._validate_path(path)
34+
self._validate_path(path, append_slash)
3335

3436
self.parameters_names = [
3537
name[1:-1] for name in re.compile(r"/[^<>]*/?").split(path) if name != ""
3638
]
3739
self.path = re.sub(r"<\w+>", r"([^/]+)", path).replace("....", r".+").replace(
3840
"...", r"[^/]+"
3941
) + ("/?" 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
4145

4246
@staticmethod
43-
def _validate_path(path: str) -> None:
47+
def _validate_path(path: str, append_slash: bool) -> None:
4448
if not path.startswith("/"):
4549
raise ValueError("Path must start with a slash.")
4650

4751
if "<>" in path:
4852
raise ValueError("All URL parameters must be named.")
4953

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]]:
5158
"""
5259
Checks if the route matches the other route.
5360
@@ -59,34 +66,34 @@ def match(self, other: "_Route") -> Tuple[bool, List[str]]:
5966
6067
Examples::
6168
62-
route = _Route("/example", GET, True)
69+
route = Route("/example", GET, True)
6370
64-
other1a = _Route("/example", GET)
65-
other1b = _Route("/example/", GET)
71+
other1a = Route("/example", GET)
72+
other1b = Route("/example/", GET)
6673
route.matches(other1a) # True, []
6774
route.matches(other1b) # True, []
6875
69-
other2 = _Route("/other-example", GET)
76+
other2 = Route("/other-example", GET)
7077
route.matches(other2) # False, []
7178
7279
...
7380
74-
route = _Route("/example/<parameter>", GET)
81+
route = Route("/example/<parameter>", GET)
7582
76-
other1 = _Route("/example/123", GET)
83+
other1 = Route("/example/123", GET)
7784
route.matches(other1) # True, ["123"]
7885
79-
other2 = _Route("/other-example", GET)
86+
other2 = Route("/other-example", GET)
8087
route.matches(other2) # False, []
8188
8289
...
8390
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)
8693
route1.matches(other1) # True, []
8794
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)
9097
route2.matches(other2) # True, []
9198
"""
9299

@@ -103,23 +110,20 @@ def __repr__(self) -> str:
103110
path = repr(self.path)
104111
methods = repr(self.methods)
105112

106-
return f"_Route(path={path}, methods={methods})"
113+
return f"Route(path={path}, methods={methods})"
107114

108115

109116
class _Routes:
110117
"""A collection of routes and their corresponding handlers."""
111118

112119
def __init__(self) -> None:
113-
self._routes: List[_Route] = []
114-
self._handlers: List[Callable] = []
120+
self._routes: List[Route] = []
115121

116-
def add(self, route: _Route, handler: Callable):
122+
def add(self, route: Route):
117123
"""Adds a route and its handler to the collection."""
118-
119124
self._routes.append(route)
120-
self._handlers.append(handler)
121125

122-
def find_handler(self, route: _Route) -> Union[Callable["...", "Response"], None]:
126+
def find_handler(self, route: Route) -> Union[Callable["...", "Response"], None]:
123127
"""
124128
Finds a handler for a given route.
125129
@@ -146,7 +150,7 @@ def route_func(request, my_parameter):
146150
if not found_route:
147151
return None
148152

149-
handler = self._handlers[self._routes.index(_route)]
153+
handler = _route.handler
150154

151155
keyword_parameters = dict(zip(_route.parameters_names, parameters_values))
152156

adafruit_httpserver/server.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
from .methods import GET, HEAD
2929
from .request import Request
3030
from .response import Response, FileResponse
31-
from .route import _Routes, _Route
31+
from .route import _Routes, Route
3232
from .status import BAD_REQUEST_400, UNAUTHORIZED_401, FORBIDDEN_403, NOT_FOUND_404
3333

3434

@@ -117,13 +117,8 @@ def route_func(request, my_parameter):
117117
def route_func(request):
118118
...
119119
"""
120-
if path.endswith("/") and append_slash:
121-
raise ValueError("Cannot use append_slash=True when path ends with /")
122-
123-
methods = set(methods) if isinstance(methods, (set, list)) else set([methods])
124-
125120
def route_decorator(func: Callable) -> Callable:
126-
self._routes.add(_Route(path, methods, append_slash), func)
121+
self._routes.add(Route(path, methods, func, append_slash=append_slash))
127122
return func
128123

129124
return route_decorator

0 commit comments

Comments
 (0)