1
|
|
|
# -*- coding: utf-8 -*- |
2
|
|
|
|
3
|
1 |
|
from collections import deque, namedtuple |
4
|
1 |
|
from threading import local |
5
|
|
|
|
6
|
1 |
|
from .injectors import ( |
7
|
|
|
DirectPrefixInjector, StaticPrefixInjector, AutoprefixInjector, |
8
|
|
|
HybrydPrefixInjector, |
9
|
|
|
) |
10
|
1 |
|
from .injectors import merge_injectors |
11
|
|
|
|
12
|
|
|
|
13
|
1 |
|
StackItem = namedtuple('StackItem', ['injector', 'parent', ]) |
14
|
|
|
|
15
|
|
|
|
16
|
1 |
|
class InjectionStack(object): |
17
|
|
|
|
18
|
1 |
|
def __init__(self, local): |
19
|
1 |
|
local.stack = deque() |
20
|
1 |
|
self._local = local |
21
|
|
|
|
22
|
1 |
|
def push(self, item): |
23
|
1 |
|
self._local.stack.append(item) |
24
|
|
|
|
25
|
1 |
|
def pop(self): |
26
|
1 |
|
return self._local.stack.pop() |
27
|
|
|
|
28
|
1 |
|
@property |
29
|
|
|
def top(self): |
30
|
1 |
|
try: |
31
|
1 |
|
return self._local.stack[-1] |
32
|
|
|
except IndexError: |
33
|
|
|
return None |
34
|
|
|
|
35
|
1 |
|
@property |
36
|
|
|
def is_empty(self): |
37
|
1 |
|
return not self._local.stack |
38
|
|
|
|
39
|
|
|
|
40
|
1 |
|
_local = local() |
41
|
1 |
|
_stack = InjectionStack(_local) |
42
|
|
|
|
43
|
|
|
|
44
|
1 |
|
class InjectionContext(object): |
45
|
|
|
|
46
|
1 |
|
def __init__(self, injector, inherit=False): |
47
|
1 |
|
if _stack.is_empty: |
48
|
1 |
|
if callable(injector): |
49
|
1 |
|
injector = injector() |
50
|
|
|
|
51
|
1 |
|
self._push(injector) |
52
|
1 |
|
elif inherit: |
53
|
1 |
|
if callable(injector): |
54
|
1 |
|
injector = injector() |
55
|
|
|
|
56
|
1 |
|
injector = merge_injectors(_stack.top.injector, injector) |
57
|
1 |
|
self._push(injector) |
58
|
|
|
|
59
|
1 |
|
def _push(self, injector): |
60
|
1 |
|
item = StackItem(injector, self) |
61
|
1 |
|
_stack.push(item) |
62
|
|
|
|
63
|
1 |
|
def __enter__(self): |
64
|
1 |
|
return _stack.top.injector |
65
|
|
|
|
66
|
1 |
|
def __exit__(self, type, value, traceback): |
67
|
1 |
|
if _stack.top.parent is self: |
68
|
1 |
|
_stack.pop() |
69
|
|
|
|
70
|
|
|
|
71
|
1 |
|
def direct_injector(prefix, inherit=False): |
72
|
1 |
|
return InjectionContext( |
73
|
|
|
lambda: DirectPrefixInjector(prefix), |
74
|
|
|
inherit) |
75
|
|
|
|
76
|
|
|
|
77
|
1 |
|
def static_injector(prefix, delimiter=None, inherit=False): |
78
|
1 |
|
return InjectionContext( |
79
|
|
|
lambda: StaticPrefixInjector(prefix, delimiter), |
80
|
|
|
inherit) |
81
|
|
|
|
82
|
|
|
|
83
|
1 |
|
def auto_injector(oid_generator=None, delimiter=None, inherit=False): |
84
|
1 |
|
return InjectionContext( |
85
|
|
|
lambda: AutoprefixInjector(oid_generator, delimiter), |
86
|
|
|
inherit) |
87
|
|
|
|
88
|
|
|
|
89
|
1 |
|
def hybrid_injector(prefix, oid_generator=None, delimiter=None, inherit=False): |
90
|
1 |
|
return InjectionContext( |
91
|
|
|
lambda: HybrydPrefixInjector(prefix, oid_generator, delimiter), |
92
|
|
|
inherit) |
93
|
|
|
|