/
bootstrap.py
271 lines (219 loc) · 9.33 KB
/
bootstrap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" :py:mod:`weblayer.bootstrap` provides :py:class:`Bootstrapper`, a helper
class that simplifies setting up and registering :ref:`weblayer` components.
To bootstrap a default configuration, pass a dictionary of settings
and list of url mappings to the :py:class:`Bootstrapper` constructor::
>>> bootstrapper = Bootstrapper(settings={}, url_mapping=[])
Then call the ``bootstrapper`` instance to register components and get
:py:class:`~weblayer.interfaces.ISettings` and
:py:class:`~weblayer.interfaces.IPathRouter` utilities. By default, the
bootstrapper uses :py:class:`~weblayer.settings.RequirableSettings` as its
:py:class:`~weblayer.interfaces.ISettings` implementation and performs a
`venusian scan`_ of the :ref:`weblayer` package to require settings declared
explicitly with :py:func:`~weblayer.settings.require_setting`. This means
that you must pass the required settings into the
:py:class:`Bootstrapper` constructor when instantiating the ``bootstrapper``
or get a ``KeyError``::
>>> settings, path_router = bootstrapper() #doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
KeyError: u'Required setting `template_directories` () is missing,
Required setting `static_files_path` () is missing,
Required setting `cookie_secret` (a long, random sequence
of bytes) is missing'
Whereas if the required settings are provided, all is well::
>>> config = {
... 'cookie_secret': '...',
... 'static_files_path': '/var/www/static',
... 'template_directories': ['templates']
... }
>>> bootstrapper = Bootstrapper(settings=config, url_mapping=[])
>>> settings, path_router = bootstrapper()
If you require your own settings (see the :py:mod:`~weblayer.settings`
module for more information), pass in the dotted names of the modules
or packages they are required in::
>>> bootstrapper = Bootstrapper(settings=config, url_mapping=[])
>>> settings, path_router = bootstrapper(packages=['foo', 'baz.bar'])
Traceback (most recent call last):
...
ImportError: No module named foo
To override specific components, either pass in ``False`` to skip
registering them, e.g.::
>>> bootstrapper = Bootstrapper(settings=config, url_mapping=[])
>>> settings, path_router = bootstrapper(TemplateRenderer=False)
Or pass in your own implementation, e.g.::
>>> from mock import Mock
>>> mock_router = Mock()
>>> bootstrapper = Bootstrapper(settings=config, url_mapping=[])
>>> settings, path_router = bootstrapper(path_router=mock_router)
>>> path_router == mock_router
True
.. _`venusian scan`: http://docs.repoze.org/venusian/
"""
__all__ = [
'Bootstrapper'
]
import imp
import sys
from os.path import dirname
from pkgutil import iter_modules
from component import registry
from interfaces import *
from auth import TrivialAuthenticationManager
from cookie import SignedSecureCookieWrapper
from method import ExposedMethodSelector
from normalise import DefaultToJSONResponseNormaliser
from route import RegExpPathRouter
from settings import RequirableSettings
from static import MemoryCachedStaticURLGenerator
from template import MakoTemplateRenderer
class Bootstrapper(object):
""" Simplifies setting up and registering :ref:`weblayer` components.
"""
def __init__(self, settings=None, url_mapping=None):
""" Stores the ``settings`` and ``url_mapping`` provided::
>>> config = {'a': 'b'}
>>> mapping = [()]
>>> b = Bootstrapper(settings=config, url_mapping=mapping)
>>> b._user_settings
{'a': 'b'}
>>> b._url_mapping
[()]
"""
if settings is None:
self._user_settings = {}
else:
self._user_settings = settings
if url_mapping is None:
self._url_mapping = []
else:
self._url_mapping = url_mapping
def __call__(
self,
packages=None,
scan_framework=True,
extra_categories=None,
require_settings=True,
**kwargs
):
""" If ``require_settings`` is ``True`` and ``settings`` isn't provided
as a keyword argument, call :py:meth:`require_settings`,
:py:meth:`register_components` and return ``settings, path_router``.
"""
if 'settings' in kwargs or not require_settings:
settings_component = kwargs.get('settings', None)
else:
settings_component = self.require_settings(
packages=packages,
scan_framework=scan_framework,
extra_categories=extra_categories
)
kwargs['settings'] = settings_component
self.register_components(**kwargs)
settings = registry.getUtility(ISettings)
path_router = registry.getUtility(IPathRouter)
return settings, path_router
def require_settings(
self,
packages=None,
scan_framework=True,
extra_categories=None
):
""" Init and return a :py:class:`~weblayer.settings.RequirableSettings`
instance, scanning ``packages`` for required settings.
"""
if packages is None:
packages = []
framework_modules = []
if scan_framework:
# only scan (non-orphaned) source files, in order to avoid scanning
# tests and examples
path = dirname(__file__)
for importer, modname, ispkg in iter_modules([path], 'weblayer.'):
loader = importer.find_module(modname)
module_type = loader.etc[2]
if module_type == imp.PY_SOURCE:
framework_modules.append(modname)
to_scan = []
for item in framework_modules + packages:
if not item in sys.modules: # pragma: no coverage
__import__(item)
to_scan.append(sys.modules[item])
settings = RequirableSettings(
packages=to_scan,
extra_categories=extra_categories
)
return settings
def register_components(
self,
settings=None,
path_router=None,
TemplateRenderer=None,
AuthenticationManager=None,
SecureCookieWrapper=None,
StaticURLGenerator=None,
MethodSelector=None,
ResponseNormaliser=None
):
""" Setup component registrations. Pass in alternative implementations
here to override, or pass in ``False`` to avoid registering a
component.
"""
if settings is not False:
if settings is None:
settings = RequirableSettings()
settings(self._user_settings)
registry.registerUtility(settings, ISettings)
if path_router is not False:
if path_router is None:
path_router = RegExpPathRouter(self._url_mapping)
registry.registerUtility(path_router, IPathRouter)
if TemplateRenderer is not False:
if TemplateRenderer is None:
TemplateRenderer = MakoTemplateRenderer
registry.registerAdapter(
TemplateRenderer,
required=[ISettings],
provided=ITemplateRenderer
)
if AuthenticationManager is not False:
if AuthenticationManager is None:
AuthenticationManager = TrivialAuthenticationManager
registry.registerAdapter(
AuthenticationManager,
required=[IRequest],
provided=IAuthenticationManager
)
if StaticURLGenerator is not False:
if StaticURLGenerator is None:
StaticURLGenerator = MemoryCachedStaticURLGenerator
registry.registerAdapter(
StaticURLGenerator,
required=[IRequest, ISettings],
provided=IStaticURLGenerator
)
if SecureCookieWrapper is not False:
if SecureCookieWrapper is None:
SecureCookieWrapper = SignedSecureCookieWrapper
registry.registerAdapter(
SecureCookieWrapper,
required=[IRequest, IResponse, ISettings],
provided=ISecureCookieWrapper
)
if MethodSelector is not False:
if MethodSelector is None:
MethodSelector = ExposedMethodSelector
registry.registerAdapter(
MethodSelector,
required=[IRequestHandler],
provided=IMethodSelector
)
if ResponseNormaliser is not False:
if ResponseNormaliser is None:
ResponseNormaliser = DefaultToJSONResponseNormaliser
registry.registerAdapter(
ResponseNormaliser,
required=[IResponse],
provided=IResponseNormaliser
)