Completed
Push — master ( e36a68...7e8a0c )
by Piotr
01:12
created

Router.__init__()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 2
rs 10
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