Completed
Push — master ( 3c3df8...1248a1 )
by Piotr
01:12
created

Router   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 24
rs 10
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A routes() 0 3 1
A dispatch() 0 4 1
A __init__() 0 2 1
A _get_endpoint_obj() 0 7 2
A _is_accepted_method() 0 3 2
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