]>
Commit | Line | Data |
---|---|---|
a4b75251 TL |
1 | import logging |
2 | ||
3 | import cherrypy | |
4 | ||
5 | from ..exceptions import ScopeNotValid | |
6 | from ..security import Scope | |
7 | from ._base_controller import BaseController | |
8 | from ._helpers import generate_controller_routes | |
9 | ||
10 | logger = logging.getLogger(__name__) | |
11 | ||
12 | ||
13 | class Router(object): | |
14 | def __init__(self, path, base_url=None, security_scope=None, secure=True): | |
15 | if security_scope and not Scope.valid_scope(security_scope): | |
16 | raise ScopeNotValid(security_scope) | |
17 | self.path = path | |
18 | self.base_url = base_url | |
19 | self.security_scope = security_scope | |
20 | self.secure = secure | |
21 | ||
22 | if self.path and self.path[0] != "/": | |
23 | self.path = "/" + self.path | |
24 | ||
25 | if self.base_url is None: | |
26 | self.base_url = "" | |
27 | elif self.base_url == "/": | |
28 | self.base_url = "" | |
29 | ||
30 | if self.base_url == "" and self.path == "": | |
31 | self.base_url = "/" | |
32 | ||
33 | def __call__(self, cls): | |
34 | cls._routed = True | |
35 | cls._cp_path_ = "{}{}".format(self.base_url, self.path) | |
36 | cls._security_scope = self.security_scope | |
37 | ||
38 | config = { | |
39 | 'tools.dashboard_exception_handler.on': True, | |
40 | 'tools.authenticate.on': self.secure, | |
41 | } | |
42 | if not hasattr(cls, '_cp_config'): | |
43 | cls._cp_config = {} | |
44 | cls._cp_config.update(config) | |
45 | return cls | |
46 | ||
47 | @classmethod | |
48 | def generate_routes(cls, url_prefix): | |
49 | controllers = BaseController.load_controllers() | |
50 | logger.debug("controllers=%r", controllers) | |
51 | ||
52 | mapper = cherrypy.dispatch.RoutesDispatcher() | |
53 | ||
54 | parent_urls = set() | |
55 | ||
56 | endpoint_list = [] | |
57 | for ctrl in controllers: | |
58 | inst = ctrl() | |
59 | for endpoint in ctrl.endpoints(): | |
60 | endpoint.inst = inst | |
61 | endpoint_list.append(endpoint) | |
62 | ||
63 | endpoint_list = sorted(endpoint_list, key=lambda e: e.url) | |
64 | for endpoint in endpoint_list: | |
65 | parent_urls.add(generate_controller_routes(endpoint, mapper, | |
66 | "{}".format(url_prefix))) | |
67 | ||
68 | logger.debug("list of parent paths: %s", parent_urls) | |
69 | return mapper, parent_urls |