-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.py
More file actions
47 lines (37 loc) · 1.45 KB
/
router.py
File metadata and controls
47 lines (37 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import json
from typing import Callable, TypeAlias, Any
from flask import Request, jsonify, abort
from service import _Data
Route: TypeAlias = Callable[[_Data], Any]
class RequestRouter:
"""Routes a request based on its path and method.
Provides `route` decorator to imitate Flask-like routing.
"""
available_methods = ("GET", "POST", "PUT", "PATCH", "DELETE")
def __init__(self) -> None:
self.functions: dict[str, dict[str, Route]] = {
method: {} for method in self.available_methods
}
def route(self, path: str, *methods: str) -> Callable[[Route], Route]:
"Associates the callable with the path and methods."
def register(f: Route) -> Route:
for method in methods:
self.functions[method][path] = f
return f
return register
def dispatch(self, request: Request) -> Any:
"""
Routes a request by calling a callable associated with
the path in the request. Returns 404 if the path has not
been associated with a callable.
"""
path = request.path
method = request.method
try:
f = self.functions[method][path]
except KeyError:
print(f"Dispatch error: {path, method}")
return abort(404)
data = json.loads(request.data) if request.data else None
print(f"Calling {f.__name__} function with data={data}.")
return jsonify(f(data))