Skip to content

Commit c0ca616

Browse files
committed
Moved previous functionality of _HTTPRequest to HTTPRoute, renamed routes to route_handlers
1 parent 450ee79 commit c0ca616

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed

adafruit_httpserver/route.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from .methods import HTTPMethod
2+
3+
4+
class HTTPRoute:
5+
def __init__(
6+
self,
7+
path: str = "",
8+
method: HTTPMethod = HTTPMethod.GET
9+
) -> None:
10+
11+
self.path = path
12+
self.method = method
13+
14+
def __hash__(self) -> int:
15+
return hash(self.method) ^ hash(self.path)
16+
17+
def __eq__(self, other: "HTTPRoute") -> bool:
18+
return self.method == other.method and self.path == other.path
19+
20+
def __repr__(self) -> str:
21+
return f"HTTPRoute(path={repr(self.path)}, method={repr(self.method)})"

adafruit_httpserver/server.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from .methods import HTTPMethod
99
from .request import HTTPRequest
1010
from .response import HTTPResponse
11+
from .route import HTTPRoute
1112
from .status import HTTPStatus
1213

1314
class HTTPServer:
@@ -22,7 +23,7 @@ def __init__(self, socket_source: Any) -> None:
2223
in CircuitPython or the `socket` module in CPython.
2324
"""
2425
self._buffer = bytearray(1024)
25-
self.routes = {}
26+
self.route_handlers = {}
2627
self._socket_source = socket_source
2728
self._sock = None
2829
self.root_path = "/"
@@ -44,7 +45,7 @@ def route_func(request):
4445
"""
4546

4647
def route_decorator(func: Callable) -> Callable:
47-
self.routes[_HTTPRequest(path, method)] = func
48+
self.route_handlers[HTTPRoute(path, method)] = func
4849
return func
4950

5051
return route_decorator
@@ -96,12 +97,17 @@ def poll(self):
9697

9798
request = HTTPRequest(raw_request=self._buffer[:length])
9899

99-
# If a route exists for this request, call it. Otherwise try to serve a file.
100-
route = self.routes.get(request, None)
101-
if route:
102-
response = route(request)
100+
handler = self.route_handlers.get(HTTPRoute(request.path, request.method), None)
101+
102+
# If a handler for route exists, call it.
103+
if handler:
104+
response = handler(request)
105+
106+
# If no handler exists and request method is GET, try to serve a file.
103107
elif request.method == HTTPMethod.GET:
104108
response = HTTPResponse(filename=request.path, root=self.root_path)
109+
110+
# If no handler exists and request method is not GET, return 500 Internal Server Error.
105111
else:
106112
response = HTTPResponse(status=HTTPStatus.INTERNAL_SERVER_ERROR)
107113

0 commit comments

Comments
 (0)