-
Notifications
You must be signed in to change notification settings - Fork 5
/
bottle_inject.py
331 lines (257 loc) · 10.3 KB
/
bottle_inject.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import functools
import inspect
import sys
__version__ = "0.1.3"
__all__ = "Plugin Injector inject".split()
py32 = sys.version_info >= (3, 2, 0)
def _makelist(data):
if isinstance(data, (tuple, list, set)):
return list(data)
elif data:
return [data]
else:
return []
class InjectError(RuntimeError):
pass
class _InjectionPoint(object):
""" The object returned by :func:`inject`. """
def __init__(self, name, config=None, implicit=False):
self.name = name
self.config = config or {}
self.implicit = implicit
def __eq__(self, other):
if isinstance(other, _InjectionPoint):
return self.__dict__ == other.__dict__
return False
class _ProviderCache(dict):
""" A self-filling cache for :meth:`Injector.resolve` results. """
def __init__(self, injector):
super(_ProviderCache, self).__init__()
self.injector = injector
def __missing__(self, func):
self[func] = value = list(self.injector._resolve(func).items())
return value
def _unwrap(func):
if inspect.isclass(func):
func = func.__init__
while hasattr(func, '__wrapped__'):
func = func.__wrapped__
return func
def _make_null_resolver(name, provider):
msg = "The dependency provider for %r does not accept configuration (it is"\
" not a resolver)." % name
def null_resolver(*a, **ka):
if a or ka:
raise InjectError(msg)
return provider
return null_resolver
class Injector(object):
def __init__(self):
self.__cache = _ProviderCache(self)
self._resolvers = {}
self._never_inject = set(('self', ))
def add_value(self, name, value, alias=()):
"""
Register a dependency value.
The dependency value is re-used for every injection and treated as a
singleton.
:param name: Name of the injection point.
:param value: The singleton to provide.
:param alias: A list of alternative injection points.
:return: None
"""
self.add_provider(name, lambda: value, alias=alias)
def add_provider(self, name, func, alias=()):
"""
Register a dependency provider.
A *provider* returns the requested dependency when called. The
provider is called with no arguments every time the dependency is
needed. It is possible to inject other dependencies into the call
signature of a provider.
:param name: Name of the injection point.
:param func: The provider callable.
:param alias: A list of alternative injection points.
:return: None
"""
self.add_resolver(name, _make_null_resolver(name, func), alias=alias)
def add_resolver(self, name, func, alias=()):
"""
Register a dependency provider resolver.
A *resolver* returns a cache-able *provider* and may accept
injection-point specific configuration. The resolver is usually
called only once per injection point and the return value is cached.
It must return a (callable) provider. It is possible to inject other
dependencies into the call signature of a resolver.
:param name: Name of the injection point.
:param func: The resolver callable.
:param alias: A list of alternative injection points.
:return: None
"""
self._resolvers[name] = func
for name in _makelist(alias):
self._resolvers[name] = func
self.__cache.clear()
def remove(self, name):
"""
Remove any dependency, provider or resolver bound to the named
injection point.
:param name: Name of the injection point to clear.
:return: None
"""
if self._resolvers.pop(name):
self.__cache.clear()
def provider(self, name, alias=()):
"""
Decorator to register a dependency provider.
See :func:`add_provider` for a description.
:param name: Name of the injection point.
:param alias: A list of alias names for this injection point.
:return: Decorator that registers the provider function to the
injector.
"""
assert isinstance(name, str)
def decorator(func):
self.add_provider(name, func, alias=alias)
return func
return decorator
def resolver(self, name, alias=()):
"""
Decorator to register a dependency provider resolver. See
:func:`add_resolver` for a description.
:param name: Name of the injection point.
:param alias: A list of alias names for this injection point.
:return: Decorator that registers the resolver to the injector.
"""
def decorator(func):
self.add_resolver(name, func, alias=alias)
return func
return decorator
def inspect(self, func):
"""
Return a dict that maps parameter names to injection points for the
provided callable.
"""
func = _unwrap(func)
if py32:
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations = inspect.getfullargspec(func)
else:
args, varargs, keywords, defaults = inspect.getargspec(func)
kwonlyargs, kwonlydefaults, annotations = [], {}, {}
defaults = defaults or ()
kwonlydefaults = kwonlydefaults or {}
injection_points = {}
# Positional arguments without default value are potential injection points,
# but marked as 'implicit'.
for arg in args[:len(args) - len(defaults or [])]:
if arg not in self._never_inject:
injection_points[arg] = _InjectionPoint(arg, implicit=True)
for arg, value in zip(args[::-1], defaults[::-1]):
if isinstance(value, _InjectionPoint):
injection_points[arg] = value
for arg, value in kwonlydefaults.items():
if isinstance(value, _InjectionPoint):
injection_points[arg] = value
for arg, value in annotations.items():
if isinstance(value, _InjectionPoint):
injection_points[arg] = value
return injection_points
def _resolve(self, func):
"""
Given a callable, return a dict that maps argument names to provider
callables. The providers are resolved and wrapped already and should
be called with no arguments to receive the injectable.
This is called by __ProviderCache.__missing__ and should not be used
in other situations.
"""
results = {}
for arg, ip in self.inspect(func).items():
results[arg] = self._prime(ip)
return results
def _prime(self, ip):
"""
Prepare a named resolver for a given injection point.
Internal use only. See _resolve()
"""
try:
provider_resolver = self._resolvers[ip.name]
except KeyError:
err = InjectError("No provider for injection point %r" % ip.name)
if not ip.implicit:
raise err
def fail_if_injected():
raise err
return fail_if_injected
provider = self.call_inject(provider_resolver, **ip.config)
return self.wrap(provider)
def call_inject(self, func, **ka):
"""
Call a function and inject missing dependencies. If you want to call
the same function multiple times, consider :method:`wrap`ing it.
"""
for key, producer in self.__cache[func]:
if key not in ka:
ka[key] = producer()
return func(**ka)
def wrap(self, func):
"""
Turn a function into a dependency managed callable.
Usage::
@injector.wrap
def my_func(db: inject('database')):
pass
or::
managed_callable = injector.wrap(my_callable)
:param func: A callable with at least one injectable parameter.
:return: A wrapped function that calls :method:`call_inject`
internally.
If the provided function does not accept any injectable parameters,
it is returned unchanged.
"""
cache = self.__cache # Avoid dot lookup in hot path
# Skip wrapping for functions with no injection points
if not self.inspect(func):
return func
@functools.wraps(func)
def wrapper(**ka):
# PERF: Inlined call_inject call.
# Keep in sync with the implementation above.
for key, producer in cache[func]:
if key not in ka:
ka[key] = producer()
return func(**ka)
wrapper.__injector__ = self
return wrapper
class Plugin(Injector):
api = 2
def __init__(self):
super(Plugin, self).__init__()
self.app = None
def setup(self, app):
from bottle import request, response
self.app = app
self.add_value('injector', self)
self.add_value('config', app.config)
self.add_value('app', app)
self.add_value('request', request, alias=['req', 'rq'])
self.add_value('response', response, alias=['res', 'rs'])
def apply(self, callback, route):
if self.inspect(callback):
return self.wrap(callback)
return callback
def inject(name, **kwargs):
"""
Mark an argument in a function signature as an injection point.
The return value can be used as an annotation (Python 3) or default
value (Python 2) for parameters that should be recognized by dependency
injection.
Usage::
def my_func(a: inject('name'),
b: inject('name', conf="val") # Resolvers only.
):
pass
:param name: Name of the dependency to inject.
:param kwargs: Additional keyword arguments passed to the dependency
provider resolver.
:return:
"""
return _InjectionPoint(name, config=kwargs)