-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdi.py
More file actions
1065 lines (838 loc) · 33.9 KB
/
di.py
File metadata and controls
1065 lines (838 loc) · 33.9 KB
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
from __future__ import unicode_literals, absolute_import, print_function
import sys
import inspect
import logging
import warnings
import functools
import contextlib
from abc import ABCMeta, abstractmethod
from collections import namedtuple, OrderedDict
from copy import copy
__major__ = 1
__minor__ = 8
__bugfix__ = 0
__version__ = '%s.%s.%s' % (__major__, __minor__, __bugfix__)
__website__ = 'http://bitbucket.org/jblawatt/python-simple-di/'
__author__ = 'Jens Blawatt'
__author_email__ = 'jblawatt@googlemail.com'
__author_website__ = 'http://www.blawatt.de/'
__maintainer__ = __author__
__maintainer_email__ = __author_email__
_logger = logging.getLogger(__name__)
__all__ = (
'DIEventDispatcher', 'DIContainer', 'attr', 'module', 'mod', 'factory',
'RelationResolver', 'ReferenceResolver', 'ModuleResolver',
'FactoryResolver', 'AttributeResolver', 'fac', 'relation', 'rel',
'reference', 'ref', 'DIConfig', 'DIConfigManager',
'ref_lazy', 'reference_lazy', 'ReferenceResolverLazy',
'mod_lazy', 'module_lazy', 'ModuleResolverLazy',
'rel_lazy', 'relation_lazy', 'RelationResolverLazy',
'factory_lazy', 'factory_lazy', 'FactoryResolverLazy',
)
py = sys.version_info
py3 = py >= (3, 0, 0)
py2 = not py3
if py3:
string_types = (str,)
else:
string_types = (str, unicode)
class DIEventDispatcher(object):
def __init__(self, container, *args, **kwargs):
self.container = container
def initialized(self, *args, **kwargs):
pass
def before_register(self, name, settings, *args, **kwargs):
pass
def after_register(self, name, settings, *args, **kwargs):
pass
def after_resolve(self, name, instance, *args, **kwargs):
pass
def before_resolve(self, name, *args, **kwargs):
pass
def before_build_up(self, name, instance, overrides, *args, **kwargs):
pass
def after_build_up(self, name, instance, overrides, *args, **kwargs):
pass
def before_resolve_type(self, name, *args, **kwargs):
pass
def after_resolve_type(self, name, type, *args, **kwargs):
pass
def after_clear(self, name):
pass
class Proxy(object):
"""
Will replaced with the real proxy instance
"""
def __init__(self, factory_method):
raise NotImplementedError()
default_config = {
'name': None,
'type': None,
'args': (),
'kwargs': {},
'singleton': False,
'lazy': True,
'properties': {},
'assert_type': None,
'factory_method': None,
'alias': [],
'mixins': []
}
class MissingConfigurationError(KeyError, AttributeError):
"""
Exception that will be raised if the requested key is not configured.
"""
def __init__(self, key):
super(MissingConfigurationError, self).__init__(
'No configuration named "%s". Please specify in '
'settings or register at runtime.' % key)
class DIConfigurationError(Exception):
"""
Error that will be raised if there is an invalid configuration given
for the di container.
"""
class DIConfig(namedtuple('DIConfigBase', default_config.keys())):
"""
This type is used for the internal configuration. Each configuration dict
becomes passed into an instance of this class.
"""
def __new__(cls, **kwargs):
type_ = kwargs.get('type')
if not type_:
raise ValueError("'type' argument is required.")
cls_kwargs = copy(default_config)
cls_kwargs.update(kwargs)
return super(DIConfig, cls).__new__(cls, **cls_kwargs)
class DIConfigManager(dict):
"""
This type is used for the internal wrapping of the settings dictionary
to control reading and temporarily delivering deviant settings for a name.
"""
context_settings = None
def __init__(self, settings_dict):
settings = OrderedDict(settings_dict.copy())
for key, config in settings.items():
if not isinstance(settings[key], DIConfig):
# create an instance of DIConfig for each config element.
# that makes it easier to work with it later.
settings[key] = DIConfig(name=key, **config)
_logger.debug(
'Created DIConfig for configuration key %s.', key)
super(DIConfigManager, self).__init__(settings)
def apply_context(self, settings):
self.context_settings = settings
def reset_context(self):
self.context_settings = None
def __getitem__(self, key):
if self.context_settings and key in self.context_settings:
return self.context_settings[key]
return super(DIConfigManager, self).__getitem__(key)
class DIContainer(object):
"""
DIContainer is a little Dependency injection container implementation.
"""
__default_value_resolver_classes = {}
def __init__(self, settings, *args, **kwargs):
"""
Creates a new DI Container.
:param settings: The dictionary, containing the container-
configuration.
:type settings: dict
"""
_logger.debug(
'Container __init__ called. Begin to bootstrap this container.')
dispatcher_type = kwargs.get('event_dispatcher', DIEventDispatcher)
self.event_dispatcher = dispatcher_type(container=self)
self.settings_type = kwargs.get('settings_type', DIConfigManager)
# If the given settings does not have the needed settings_type
# wrap them with it.
if isinstance(settings, self.settings_type):
self.settings = settings
else:
self.settings = self.settings_type(settings)
self.singletons = {}
self.parent = kwargs.get('parent', None)
# assign default resolvers. better use a resolver instance.
# maybe remove this in some version.
self.value_resolvers = dict(
(key, k.as_resolve_method(self))
for key, k in self.__default_value_resolver_classes.items()
)
# check if individual value_resolves are given. update the internal
# resolver dictionary with this values.
if 'value_resolvers' in kwargs:
_logger.debug('Updating value_resolvers with the given ones.')
warnings.warn(
'"value_resolvers" is deprecated. '
'Use a Resolver instance in your configuration.',
DeprecationWarning)
self.value_resolvers.update(kwargs.get('value_resolvers'))
_logger.debug('checking for non-lazy configrations.')
for key, conf in self.settings.items():
if not conf.lazy:
_logger.debug(
'found non-lazy configuration %s. resovling it.', key)
self.resolve(key)
# set the proxy type name
self.proxy_type_name = kwargs.get(
'proxy_type_name', 'lazy_object_proxy.Proxy')
self.event_dispatcher.initialized()
@classmethod
def add_value_resolver(cls, resolver_class):
# type: (DIContainer, Resolver) -> None
# Add resolver classes from outside of the dicontainer.
# Once they where registered in the __init__.
key = resolver_class.key
cls.__default_value_resolver_classes[key] = \
resolver_class
@staticmethod
def import_module(name, package=None):
"""
Internal method to wrap the import_module function.
"""
_logger.debug(
'calling import_module with name=%s, package=%s.', name, package)
from importlib import import_module
return import_module(name, package)
# ---------------------------
# private methods
# ---------------------------
def _resolve_type(self, python_name, mixins=None):
"""
Resolves a type. The Parameter :code:`python_name` is the
types full path python name.
* de.blawatt.test.Person
The types module can dynamicly be added to the path this way:
* /tmp/dir_with_module/:module.Person
:param python_name: The full name of the type to reslove.
:type python_name: str|unicode
:param mixins: tist or tuple of types to mixin.
:type mixins: list|tuple
:returns: type
"""
# check if python_name contains a : to split path
# and python_name
_logger.debug('resolving type "%s."', python_name)
def _import(type_path, type_name):
mod = self.import_module(type_path)
return getattr(mod, type_name)
if (py2 and isinstance(python_name, string_types)) or \
(py3 and isinstance(python_name, str)):
if ':' in python_name:
# fix for windows. drive is splitte with the same sign:
# "c:\....:modulename.ClassName".
path, python_name = python_name.rsplit(':', 1)
if path not in sys.path:
sys.path.append(path)
try:
type_path, type_name = python_name.rsplit('.', 1)
except ValueError:
if py3:
type_path = 'builtins'
type_name = python_name
else: # 2.x
type_path = '__builtin__'
type_name = python_name
type_ = _import(type_path, type_name)
elif isinstance(python_name, (list, tuple)):
# FIXME: this is not covered. for what isit?
if len(python_name) == 3:
path, type_path, type_name = python_name
if path not in sys.path:
sys.path.append(path)
else:
type_path, type_name = python_name
type_ = _import(type_path, type_name)
else:
type_ = python_name
if mixins:
mixed_types = map(self._resolve_type, mixins)
mixed_types = tuple(mixed_types)
type_ = type(
str("ComputedType"),
mixed_types + (type_,), {})
return type_
def _resolve_value(self, value_conf):
"""
resolves a value from a string.
depeding on then value prefix some furthur action will follow:
* ''rel'': relates to anoter type of in this container.
* ''mod'': imports and return a module/package with that name.
* ''ref'': load a variable off a module/package.
* ''attr'':
* ''factory'':
:param value_conf: the value to pass or resolve.
:type value_conf: dict
:returns: object
"""
value = value_conf
if isinstance(value, Resolver):
return value.resolve(self)
if isinstance(value_conf, string_types):
for key, resolver in self.value_resolvers.items():
if value_conf.startswith('%s:' % key):
return resolver(value_conf)
return value
def _resolve_args(self, conf_args, conf_kwargs):
"""
resolves the arguments off the container configuration.
:param conf: value configuration.
:type conf: dict
:returns: (), {}
"""
args = []
kwargs = {}
# copy given references of dictionaries to not change
# references values.
conf_args = conf_args and copy(conf_args) or ()
conf_kwargs = conf_kwargs and copy(conf_kwargs) or {}
if isinstance(conf_args, dict) and conf_kwargs:
warnings.warn(
'Using "args" as dictionary is deprecated and will '
'be removed in DI > 2.0',
DeprecationWarning
)
# if there is still an empty key in args dictioanry
# we will keep this in args and move the rest to the kwargs
# dictionary. legacy reason :-(.
if isinstance(conf_args, dict):
conf_kwargs = dict(**conf_kwargs)
conf_kwargs.update({
(k, v) for k, v in conf_args.items() if k != ''
})
conf_args = conf_args.pop('', tuple())
# resolve items of kwargs values.
for key, value_conf in conf_kwargs.items():
kwargs[key] = self._resolve_value(value_conf)
# resolve items of args values.
for value_conf in conf_args:
args.append(self._resolve_value(value_conf))
return args, kwargs
def _check_type(self, conf_name, type_, expected):
"""
Check if `type_` is a subclass of `expected`.
:param conf_name: Name of the Configuration name for this check.
:type conf_name: str
:param type_: Type that must implement the expected type.
:type type_: type
:param expected: Type that must be implemented by `type_`.
:type expected: type
:raises: TypeError
"""
if not issubclass(type_, expected):
raise TypeError(
'%s is not a subclass of %s. This violates the '
'configuration for key %s'
% (type_, expected, conf_name)
)
def get_proxy_type(self):
"""
Returns the Proxy type, used for lazy resolving.
:return: The type used as Proxy.
:rtype: di.Proxy
"""
try:
proxy_type = self._resolve_type(self.proxy_type_name)
except ImportError:
# We do not provide lazy-object-proxy because of different licences.
raise ImportError(
'got an error while importing the proxy type `%s`. '
'make sure you installed `lazy-object-proxy` or another '
'lazy object implementation. (i.e. django.utils.functional'
'.SimpleLazyObject).' % self.proxy_type_name)
return proxy_type
# ---------------------------
# public methods
# ---------------------------
def register(self, name, settings=None, replace=False):
"""
register a new configuration at runtime.
can be used as decorator if the `type` key in the settings is left
empty. so the type will be set.
:param name: the name for the new configuration.
:type name: str, unicode
:param settings: the sessings dictionary for the new type.
:type settings: dict, di.DIConfig
:param replace: defines weather a existing configuration should be
replaced with this.
:type replace: bool
"""
self.event_dispatcher.before_register(name=name, settings=settings)
# check if this function is used as decorator. the indicator is,
# calling the function with settings but without type even leave
# settings empty.
is_decorator = (settings is None or (isinstance(
settings, dict) and 'type' not in settings))
if is_decorator:
def wrapper(func_or_type):
# register the given type.
self.register(name, dict(settings or {},
type=func_or_type), replace)
return func_or_type
return wrapper
if name in self.settings:
if replace:
_logger.debug(
"name %s is already reagisterd. will be replaced.", name)
else:
raise KeyError(
'there is already a configuration with this name.')
if isinstance(settings, dict):
conf = DIConfig(name=name, **settings)
else:
conf = settings
self.settings[name] = conf
if name in self.singletons:
del self.singletons[name]
self.event_dispatcher.after_register(name=name, settings=conf)
def resolve(self, name, *instance_args, **instance_kwargs):
"""
Resolves an object by its name assigned in the configuration.
:param name: object's name in the configuration.
:type name: str|unicode
:returns: object
"""
self.event_dispatcher.before_resolve(name=name)
# if there is no string provided as name, di will try to
# resolve the first configured instance with the given type.
if not isinstance(name, string_types):
for obj in self.resolve_many(
name, *instance_args, **instance_kwargs):
return obj
else:
raise MissingConfigurationError(str(name))
# check if there already is a singleton instance
# for this name
if name in self.singletons:
return self.singletons[name]
try:
# load information to create the instance
conf = self.settings[name]
except KeyError:
# name could not ne found. let us try to
# find it by it's aliasname.
settings = self.settings
settings_iter = (settings.items if py3 else settings.iteritems)
for key, conf in settings_iter():
if name in conf.alias:
_logger.debug(
"%s could not be found. found it as alias for %s.",
name, key)
name = key
break
else:
# no configuration with this name as alias could
# be found. so we reraise the origin exception.
raise MissingConfigurationError(name)
# found the name for the given alias. so check if
# there is a singleton instance for it.
if name in self.singletons:
return self.singletons[name]
type_ = self._resolve_type(conf.type, mixins=conf.mixins)
# assert weather the type implements the
# configures basetype.
assert_type = conf.assert_type
if assert_type:
expected_type = self._resolve_type(assert_type)
self._check_type(name, type_, expected_type)
# check if we got some arguments to pass into the
# new instance constructor.
if instance_args or instance_kwargs:
_args, _kwargs = (instance_args, instance_kwargs)
else:
# resolve the arguments to pass into the constructor
_args, _kwargs = self._resolve_args(conf.args, conf.kwargs)
# create the instance
if conf.factory_method:
obj = getattr(type_, conf.factory_method)(*_args, **_kwargs)
else:
obj = type_(*_args, **_kwargs)
obj = self.build_up(name, obj)
# save instance to singleton container
if conf.singleton:
self.singletons[name] = obj
self.event_dispatcher.after_resolve(name=name, instance=obj)
return obj
def resolve_many(self, base_type, *instance_args, **instance_kwargs):
"""
Returns a generator of all instances which types is a subclass
of the given `base_type`.
:param base_type: the type every objects type should be a subclass of.
:type base_type: str | type
:param instance_args: arguments that should be passed as constructor args.
:type instance_args: tuple
:param instance_kwargs: keyword arguments that should be passed as
constructor kwargs.
:type instance_kwargs: dict
"""
if isinstance(base_type, string_types):
base_type = self._resolve_type(base_type)
for name, conf in self.settings.items():
instance_type = conf.type
if isinstance(instance_type, string_types):
instance_type = self._resolve_type(
instance_type, mixins=conf.mixins)
if issubclass(instance_type, base_type):
yield self.resolve(name, *instance_args, **instance_kwargs)
def resolve_many_lazy(self, base_types, *instance_args, **instance_kwargs):
"""
Returns an object proxy to lazy resolve multiple objects.
:param base_type: the type every objects type should be a subclass of.
:type base_type: str | type
:param instance_args: arguments that should be passed as constructor args.
:type instance_args: tuple
:param instance_kwargs: keyword arguments that should be passed as
constructor kwargs.
:type instance_kwargs: dict
"""
proxy_type = self.get_proxy_type()
return proxy_type(lambda: self.resolve_many(base_types, *instance_args, **instance_kwargs))
def resolve_lazy(self, name, *instance_args, **instance_kwargs):
"""
Return an object proxy to the to lazy resolve requested instance.
:param name: object's name in the configuration.
:type name: str|unicode
:return: The proxy object to lazy access the instance.
:rtype: di.Proxy
"""
proxy_type = self.get_proxy_type()
return proxy_type(lambda: self.resolve(name, *instance_args, **instance_kwargs))
def resolve_type(self, name):
"""
Resolves a type for the given name in the configuration.
:param name: name of an object in the configuration.
:type name: str|unicode
:returns: type
:rtype: type
"""
self.event_dispatcher.before_resolve_type(name=name)
try:
# try to resolve the configuration by name.
conf = self.settings[name]
except KeyError:
# if htere is a parent given, check if there is a configuration
# for this name. otherwise raise an exception.
if self.parent is not None:
return self.parent.resolve(name)
else:
raise MissingConfigurationError(name)
type_ = self._resolve_type(conf.type, mixins=conf.mixins)
self.event_dispatcher.after_resolve_type(name=name, type=type_)
return type_
def resolve_type_lazy(self, name):
"""
Lazy resolves a type for the given name in the configuration.
:param name: name of an object in the configuration.
:type name: str|unicode
:return: The proxy object to lazy access the type.
:rtype: lazy_object_proxy.Proxy
"""
proxy_type = self.get_proxy_type()
return proxy_type(lambda: self.resolve_type(name))
def build_up(self, name, instance, **overrides):
"""
Injects the information spezified in the properties config
into an existing object.
:param name: name of the object definition in the container config.
:type name: str
:param instance: the instance to buildup
:type instance: object
:param **overrides: sets/overrides the information of the config
with the given information.
:returns: the buildup instance
"""
self.event_dispatcher.before_build_up(
name=name, instance=instance, overrides=overrides
)
conf = self.settings[name]
prop = conf.properties.copy()
prop.update(overrides)
for key, value in prop.items():
setattr(instance, key, self._resolve_value(value))
self.event_dispatcher.after_build_up(
name=name, instance=instance, overrides=overrides
)
return instance
def clear(self, name=None):
"""
Deletes all or the given singleton instances.
:param name: the name of the singleton instance that shoud be
destroied.
:type name: str
"""
if name is not None:
if name in self.singletons:
del self.singletons[name]
else:
self.singletons = {}
self.event_dispatcher.after_clear(name=name)
def create_child_container(self, *args, **kwargs):
"""
Creates a child container with the given Configuration
:returns: a new container instance on this type.
:rtype: di.DIContainer
"""
kwargs['parent'] = self
return type(self)(*args, **kwargs)
@contextlib.contextmanager
def context(self, settings):
"""
Use this container in a contextual block an replace / extend the
the settings for this.
:param settings: Settings that will be used in this Context.
:type settings: dict
"""
if not isinstance(settings, DIConfigManager):
settings = DIConfigManager(settings)
self.settings.apply_context(settings)
yield
self.settings.reset_context()
def __dir__(self):
"""
Override the base dir and extend with the configuration names.
:returns: list of strings
"""
d = []
d.extend(dir(type(self)))
d.extend(self.__dict__.keys())
d.extend(self.settings.keys())
return list(set(d))
def __getattr__(self, name):
"""
Resolves the given name in this container.
DEPRECATED: This method is deprecated and will be removed in 2.0.
Please use the method `resolve`.
:param name: the key to resolve.
:type name: str
:returns: object
:rtype: object
"""
warnings.warn(
"Resolving objects over __getattr__ is deprecated and will be "
"removed in 2.0. Please use the method `resolve` instead.",
DeprecationWarning)
try:
# try to resolve in this container.
return self.resolve(name)
except MissingConfigurationError as error:
# If this containers has a parent container lookup there
# or reraise the exception.
if self.parent is not None:
return self.parent.resolve(name)
else:
raise error
def _inject(self, resolve_method, force=False, **inject_kwargs):
def wrapper(func):
@functools.wraps(func)
def inner(*args, **kwargs):
# if args are given we map the args to the kwargs to
# ensure wie set the right values.
if args:
args_spec = inspect.getargspec(func)
for i, arg_value in enumerate(args):
kwargs[args_spec.args[i]] = arg_value
for key, name in inject_kwargs.items():
if force or key not in kwargs:
kwargs[key] = resolve_method(name)
_logger.debug(
'calling decorated function %s with %s.',
func.__name__, kwargs)
return func(**kwargs)
return inner
return wrapper
def inject(self, force=False, **inject_kwargs):
"""
this method that can be used as decorator for another function.
it can inject values from the container to keyworkd arguments,
given in the **inject_kwargs.
:param force: defines if the given value should be overwritten with
the containers value. default: False.
:type force: bool
:rtype: types.FunctionType
"""
return self._inject(self.resolve, force, **inject_kwargs)
def inject_many(self, force=False, **inject_kwargs):
"""
this method that can be used as decorator for another function.
it can inject values from the container to keyworkd arguments,
given in the **inject_kwargs.
:param force: defines if the given value should be overwritten with
the containers value. default: False.
:type force: bool
:rtype: types.FunctionType
"""
return self._inject(self.resolve_many, force, **inject_kwargs)
class Resolver(object):
__metaclass__ = ABCMeta
key = ''
def __init__(self, value_conf):
"""
:param value_conf: argument configuration string.
:type value_conf: str, unicode
"""
if value_conf.startswith('{key}:'.format(key=self.key)):
self.value_conf = value_conf[len(self.key) + 1:]
else:
self.value_conf = value_conf
@abstractmethod
def resolve(self, container):
"""
:param container: a dicontainer instance
:type container: di.DIContainer
"""
raise NotImplementedError()
@classmethod
def as_resolve_method(cls, container):
def _inner(value_conf):
return cls(value_conf).resolve(container)
return _inner
class LazyResolverMixin(object):
"""
Resolver Mixin to let resolvers provide lazy object
for the requested value.
"""
@property
def key(self):
return '{key}_lazy'.format(key=super(LazyResolverMixin, self).key)
def resolve(self, container):
@functools.wraps(super(LazyResolverMixin, self).resolve)
def _inner():
# wraps origin method to provide lazy resolution.
return super(LazyResolverMixin, self).resolve(container)
proxy_type = container.get_proxy_type()
return proxy_type(_inner)
class ReferenceResolver(Resolver):
key = 'ref'
def resolve(self, container):
"""
Resolves a value by pythonpath.
:type container: di.DIContainer
:param container:
:rtype: object
"""
try:
mod_name, var_name = self.value_conf.rsplit('.', 1)
except ValueError:
# to many values to unpack. no . in it.
return container.import_module(self.value_conf)
else:
mod = container.import_module(mod_name)
return getattr(mod, var_name)
reference = ref = ReferenceResolver
reference_lazy = ref_lazy = ReferenceResolverLazy = \
type(str('ReferenceResolverLazy'), (LazyResolverMixin, ReferenceResolver), {})
class RelationResolver(Resolver):
key = 'rel'
def resolve(self, container):
"""
:type container: di.DIContainer
:param container: The Container Instance to lookup in.
:rtype: object
"""
return container.resolve(self.value_conf)
relation = rel = RelationResolver
relation_lazy = rel_lazy = RelationResolverLazy = \
type(str('RelationResolverLazy'), (LazyResolverMixin, RelationResolver), {})
class ModuleResolver(Resolver):
key = 'mod'
def resolve(self, container):
"""
:type container: di.DIContainer
:param container: The Container Instancze to resolve with.
:rtype: object
"""
return container.import_module(self.value_conf)
module = mod = ModuleResolver
module_lazy = mod_lazy = ModuleResolverLazy = \
type(str('ModuleResolverLazy'), (LazyResolverMixin, ModuleResolver), {})
class FactoryResolver(Resolver):
key = 'factory'
def resolve(self, container):
"""
:type container: di.DIContainer
:param container:
:rtype: object
"""
mod_name, factory_name = self.value_conf.rsplit('.', 1)
mod = container.import_module(mod_name)
return getattr(mod, factory_name)()
fac = factory = FactoryResolver
fac_lazy = factory_lazy = FactoryResolverLazy = \
type(str('FactoryResolverLazy'), (LazyResolverMixin, FactoryResolver), {})
class AttributeResolver(Resolver):
key = 'attr'
def resolve(self, container, lazy=False):
"""
:type container: di.DIContainer
:param container:
:rtype: object
"""
pre_conf, attr_name = self.value_conf.rsplit('.', 1)
instance = ReferenceResolver(pre_conf).resolve(container)
return getattr(instance, attr_name)
attr = attribute = AttributeResolver
attr_lazy = attribute_lazy = AttributeResolverLazy = \
type(str('AttributeResolverLazy'), (LazyResolverMixin, AttributeResolver), {})
# Register resolvers to use 'key:'-Shortcuts
DIContainer.add_value_resolver(AttributeResolver)
DIContainer.add_value_resolver(RelationResolver)
DIContainer.add_value_resolver(ReferenceResolver)
DIContainer.add_value_resolver(ModuleResolver)
DIContainer.add_value_resolver(FactoryResolver)
DIContainer.add_value_resolver(AttributeResolverLazy)
DIContainer.add_value_resolver(RelationResolverLazy)
DIContainer.add_value_resolver(ReferenceResolverLazy)
DIContainer.add_value_resolver(ModuleResolverLazy)
DIContainer.add_value_resolver(FactoryResolverLazy)
_DEFAULT_CONTAINER = None
def set_default_container(container):