1
|
|
|
import abc |
2
|
|
|
from typing import Callable, List |
3
|
|
|
|
4
|
|
|
import werkzeug.exceptions |
5
|
|
|
from werkzeug.routing import Map, Rule |
6
|
|
|
|
7
|
|
|
from mountapi.core import exceptions |
8
|
|
|
from mountapi.endpoints import AbstractEndpoint |
9
|
|
|
|
10
|
|
|
|
11
|
|
|
class Route(Rule): |
12
|
|
|
def __init__(self, path, endpoint) -> None: |
13
|
|
|
self.path = path |
14
|
|
|
super().__init__(path, endpoint=endpoint) |
15
|
|
|
|
16
|
|
|
|
17
|
|
|
class AbstractRouter(exceptions.NotImplementedMixin, metaclass=abc.ABCMeta): |
18
|
|
|
@property |
19
|
|
|
@abc.abstractmethod |
20
|
|
|
def routes(self) -> List[Route]: |
21
|
|
|
raise self.not_implemented() |
22
|
|
|
|
23
|
|
|
@abc.abstractmethod |
24
|
|
|
def dispatch(self, path: str, method: str) -> Callable: |
25
|
|
|
raise self.not_implemented() |
26
|
|
|
|
27
|
|
|
|
28
|
|
|
class Router(AbstractRouter): |
29
|
|
|
@property |
30
|
|
|
def routes(self) -> List[Route]: |
31
|
|
|
return list(self._adapter.map.iter_rules()) |
32
|
|
|
|
33
|
|
|
def __init__(self, routes: list) -> None: |
34
|
|
|
self._adapter = Map(routes).bind('') |
35
|
|
|
|
36
|
|
|
def dispatch(self, path: str, method: str) -> Callable: |
37
|
|
|
endpoint_obj = self._get_endpoint_obj(path) |
38
|
|
|
self._is_accepted_method(endpoint_obj, method) |
39
|
|
|
return getattr(endpoint_obj, method.lower()) |
40
|
|
|
|
41
|
|
|
def _get_endpoint_obj(self, path: str) -> AbstractEndpoint: |
42
|
|
|
try: |
43
|
|
|
endpoint_cls, kwargs = self._adapter.match(path) |
44
|
|
|
except werkzeug.exceptions.NotFound: |
45
|
|
|
raise exceptions.NotFound |
46
|
|
|
|
47
|
|
|
return endpoint_cls(**kwargs) |
48
|
|
|
|
49
|
|
|
def _is_accepted_method(self, endpoint_obj: AbstractEndpoint, method: str): |
50
|
|
|
if method not in endpoint_obj.accepted_methods: |
51
|
|
|
raise exceptions.MethodNotAllowed |
52
|
|
|
|