|
1
|
|
|
import abc |
|
2
|
|
|
from typing import Callable |
|
3
|
|
|
|
|
4
|
|
|
import werkzeug.exceptions |
|
5
|
|
|
from werkzeug.routing import Map, Rule |
|
6
|
|
|
|
|
7
|
|
|
from mountapi.core import exceptions |
|
8
|
|
|
|
|
9
|
|
|
|
|
10
|
|
|
class Route(Rule): |
|
11
|
|
|
def __init__(self, path, endpoint) -> None: |
|
12
|
|
|
super().__init__(path, endpoint=endpoint) |
|
13
|
|
|
|
|
14
|
|
|
|
|
15
|
|
|
class AbstractRouter(metaclass=abc.ABCMeta): |
|
16
|
|
|
@abc.abstractmethod |
|
17
|
|
|
def dispatch(self, path: str, method: str) -> Callable: |
|
18
|
|
|
raise NotImplementedError('dispatch method has to be implemented.') |
|
19
|
|
|
|
|
20
|
|
|
|
|
21
|
|
|
class Router(AbstractRouter): |
|
22
|
|
|
def __init__(self, routes: list) -> None: |
|
23
|
|
|
self._adapter = Map(routes).bind('') |
|
24
|
|
|
|
|
25
|
|
|
def dispatch(self, path: str, method: str) -> Callable: |
|
26
|
|
|
endpoint_cls = self._get_endpoint_cls(path, method) |
|
27
|
|
|
return getattr(endpoint_cls, method.lower()) |
|
28
|
|
|
|
|
29
|
|
|
def _get_endpoint_cls(self, path: str, method: str) -> object: |
|
30
|
|
|
try: |
|
31
|
|
|
endpoint_cls, kwargs = self._adapter.match(path, method) |
|
32
|
|
|
except werkzeug.exceptions.NotFound: |
|
33
|
|
|
raise exceptions.NotFound |
|
34
|
|
|
|
|
35
|
|
|
if method in endpoint_cls.accepted_methods: |
|
36
|
|
|
return endpoint_cls |
|
37
|
|
|
else: |
|
38
|
|
|
raise exceptions.MethodNotAllowed |
|
39
|
|
|
|