2015-03-09 01:01:39 +03:00
|
|
|
"""Injections module."""
|
2015-01-10 12:24:25 +03:00
|
|
|
|
2015-08-03 12:57:42 +03:00
|
|
|
from six import wraps
|
|
|
|
|
2015-03-11 16:18:42 +03:00
|
|
|
from .utils import is_provider
|
2015-08-03 12:57:42 +03:00
|
|
|
from .utils import ensure_is_injection
|
|
|
|
from .utils import get_injectable_kwargs
|
2015-03-11 16:18:42 +03:00
|
|
|
|
2015-01-10 12:24:25 +03:00
|
|
|
|
|
|
|
class Injection(object):
|
2015-03-09 01:01:39 +03:00
|
|
|
|
|
|
|
"""Base injection class."""
|
2015-01-10 12:24:25 +03:00
|
|
|
|
2015-07-22 10:53:16 +03:00
|
|
|
__IS_INJECTION__ = True
|
2015-07-11 23:34:23 +03:00
|
|
|
__slots__ = ('name', 'injectable')
|
2015-03-11 16:18:42 +03:00
|
|
|
|
2015-07-11 23:34:23 +03:00
|
|
|
def __init__(self, name, injectable):
|
2015-03-09 01:01:39 +03:00
|
|
|
"""Initializer."""
|
2015-01-10 12:24:25 +03:00
|
|
|
self.name = name
|
|
|
|
self.injectable = injectable
|
|
|
|
|
2015-01-11 16:03:45 +03:00
|
|
|
@property
|
|
|
|
def value(self):
|
2015-03-09 01:01:39 +03:00
|
|
|
"""Return injectable value."""
|
2015-07-11 23:34:23 +03:00
|
|
|
if is_provider(self.injectable):
|
2015-01-11 16:03:45 +03:00
|
|
|
return self.injectable()
|
|
|
|
return self.injectable
|
2015-01-10 12:24:25 +03:00
|
|
|
|
|
|
|
|
2015-03-23 02:04:18 +03:00
|
|
|
class KwArg(Injection):
|
2015-03-09 01:01:39 +03:00
|
|
|
|
2015-03-23 02:04:18 +03:00
|
|
|
"""Keyword argument injection."""
|
2015-01-10 12:24:25 +03:00
|
|
|
|
2015-07-22 10:53:16 +03:00
|
|
|
__IS_KWARG_INJECTION__ = True
|
2015-03-11 16:18:42 +03:00
|
|
|
|
2015-01-10 12:24:25 +03:00
|
|
|
|
|
|
|
class Attribute(Injection):
|
2015-03-09 01:01:39 +03:00
|
|
|
|
|
|
|
"""Attribute injection."""
|
2015-01-10 12:24:25 +03:00
|
|
|
|
2015-07-22 10:53:16 +03:00
|
|
|
__IS_ATTRIBUTE_INJECTION__ = True
|
2015-03-11 16:18:42 +03:00
|
|
|
|
2015-01-10 12:24:25 +03:00
|
|
|
|
|
|
|
class Method(Injection):
|
2015-03-09 01:01:39 +03:00
|
|
|
|
|
|
|
"""Method injection."""
|
2015-03-11 16:18:42 +03:00
|
|
|
|
2015-07-22 10:53:16 +03:00
|
|
|
__IS_METHOD_INJECTION__ = True
|
2015-08-03 12:57:42 +03:00
|
|
|
|
|
|
|
|
|
|
|
def inject(injection):
|
|
|
|
"""Dependency injection decorator.
|
|
|
|
|
|
|
|
:type injection: Injection
|
|
|
|
:return: (callable) -> (callable)
|
|
|
|
"""
|
|
|
|
injection = ensure_is_injection(injection)
|
|
|
|
|
|
|
|
def decorator(callback):
|
|
|
|
"""Dependency injection decorator."""
|
|
|
|
if hasattr(callback, '_injections'):
|
|
|
|
callback._injections += (injection,)
|
|
|
|
|
|
|
|
@wraps(callback)
|
|
|
|
def decorated(*args, **kwargs):
|
|
|
|
"""Decorated with dependency injection callback."""
|
|
|
|
return callback(*args,
|
|
|
|
**get_injectable_kwargs(kwargs,
|
|
|
|
getattr(decorated,
|
|
|
|
'_injections')))
|
|
|
|
|
|
|
|
setattr(decorated, '_injections', (injection,))
|
|
|
|
|
|
|
|
return decorated
|
|
|
|
return decorator
|