-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtoolbox.py
388 lines (254 loc) · 10.1 KB
/
toolbox.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
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
import logging
import sys
from collections import OrderedDict
from types import ModuleType
from typing import Dict, Union, List, Tuple, Any, Optional
from django.contrib import admin
from django.contrib.admin import AdminSite
from django.db import DatabaseError
from django.db.models import Model, Field
from .exceptions import SitePrefsException
from .models import Preference
from .signals import prefs_save
from .utils import import_prefs, get_frame_locals, traverse_local_prefs, get_pref_model_admin_class, \
get_pref_model_class, PrefProxy, PatchedLocal, Frame
__PATCHED_LOCALS_SENTINEL = '__siteprefs_locals_patched'
__PREFS_REGISTRY = None
__PREFS_DEFAULT_REGISTRY = OrderedDict()
__MODELS_REGISTRY = {}
LOGGER = logging.getLogger(__name__)
def on_pref_update(*args, **kwargs):
"""Triggered on dynamic preferences model save.
Issues DB save and reread.
"""
Preference.update_prefs(*args, **kwargs)
Preference.read_prefs(get_prefs())
prefs_save.connect(on_pref_update)
def get_prefs() -> dict:
"""Returns a dictionary with all preferences discovered by siteprefs."""
global __PREFS_REGISTRY
if __PREFS_REGISTRY is None:
__PREFS_REGISTRY = __PREFS_DEFAULT_REGISTRY
return __PREFS_REGISTRY
def get_app_prefs(app: str = None) -> dict:
"""Returns a dictionary with preferences for a certain app/module.
:param app:
"""
if app is None:
with Frame(stepback=1) as frame:
app = frame.f_globals['__name__'].split('.')[0]
prefs = get_prefs()
if app not in prefs:
return {}
return prefs[app]
def get_prefs_models() -> Dict[str, Model]:
"""Returns registered preferences models indexed by application names."""
return __MODELS_REGISTRY
def bind_proxy(
values: Union[List, Tuple],
category: str = None,
field: Field = None,
verbose_name: str = None,
help_text: str = '',
static: bool = True,
readonly: bool = False
) -> List[PrefProxy]:
"""Binds PrefProxy objects to module variables used by apps as preferences.
:param values: Preference values.
:param category: Category name the preference belongs to.
:param field: Django model field to represent this preference.
:param verbose_name: Field verbose name.
:param help_text: Field help text.
:param static: Leave this preference static (do not store in DB).
:param readonly: Make this field read only.
"""
addrs = OrderedDict()
depth = 3
for local_name, locals_dict in traverse_local_prefs(depth):
addrs[id(locals_dict[local_name])] = local_name
proxies = []
locals_dict = get_frame_locals(depth)
for value in values: # Try to preserve fields order.
id_val = id(value)
if id_val in addrs:
local_name = addrs[id_val]
local_val = locals_dict[local_name]
if isinstance(local_val, PatchedLocal) and not isinstance(local_val, PrefProxy):
proxy = PrefProxy(
local_name, value.val,
category=category,
field=field,
verbose_name=verbose_name,
help_text=help_text,
static=static,
readonly=readonly,
)
app_name = locals_dict['__name__'].split('.')[-2] # x.y.settings -> y
prefs = get_prefs()
if app_name not in prefs:
prefs[app_name] = OrderedDict()
prefs[app_name][local_name.lower()] = proxy
# Replace original pref variable with a proxy.
locals_dict[local_name] = proxy
proxies.append(proxy)
return proxies
def register_admin_models(admin_site: AdminSite):
"""Registers dynamically created preferences models for Admin interface.
:param admin_site: AdminSite object.
"""
global __MODELS_REGISTRY
prefs = get_prefs()
for app_label, prefs_items in prefs.items():
model_class = get_pref_model_class(app_label, prefs_items, get_app_prefs)
if model_class is not None:
__MODELS_REGISTRY[app_label] = model_class
admin_site.register(model_class, get_pref_model_admin_class(prefs_items))
def autodiscover_siteprefs(admin_site: AdminSite = None):
"""Automatically discovers and registers all preferences available in all apps.
:param admin_site: Custom AdminSite object.
"""
import_prefs()
try:
Preference.read_prefs(get_prefs())
except DatabaseError:
# This may occur if run from manage.py (or its wrapper) when db is not yet initialized.
LOGGER.warning('Unable to read preferences from database. Skip.')
else:
if admin_site is None:
admin_site = admin.site
register_admin_models(admin_site)
def patch_locals(depth: int = 2):
"""Temporarily (see unpatch_locals()) replaces all module variables
considered preferences with PatchedLocal objects, so that every
variable has different hash returned by id().
"""
for name, locals_dict in traverse_local_prefs(depth):
locals_dict[name] = PatchedLocal(name, locals_dict[name])
get_frame_locals(depth)[__PATCHED_LOCALS_SENTINEL] = True # Sentinel.
def unpatch_locals(depth: int = 3):
"""Restores the original values of module variables
considered preferences if they are still PatchedLocal
and not PrefProxy.
"""
for name, locals_dict in traverse_local_prefs(depth):
if isinstance(locals_dict[name], PatchedLocal):
locals_dict[name] = locals_dict[name].val
del get_frame_locals(depth)[__PATCHED_LOCALS_SENTINEL]
class ModuleProxy:
"""Proxy to handle module attributes access."""
def __init__(self):
self._module: Optional[ModuleType] = None
self._prefs = []
def bind(self, module: ModuleType, prefs: List[str]):
"""
:param module:
:param prefs: Preference names. Just to speed up __getattr__.
"""
self._module = module
self._prefs = set(prefs)
def __getattr__(self, name: str) -> Any:
value = getattr(self._module, name)
if name in self._prefs:
# It is a PrefProxy
value = value.value
return value
def proxy_settings_module(depth: int = 3):
"""Replaces a settings module with a Module proxy to intercept
an access to settings.
:param depth: Frame count to go backward.
"""
proxies = []
modules = sys.modules
module_name = get_frame_locals(depth)['__name__']
module_real = modules[module_name]
for name, locals_dict in traverse_local_prefs(depth):
value = locals_dict[name]
if isinstance(value, PrefProxy):
proxies.append(name)
new_module = type(module_name, (ModuleType, ModuleProxy), {})(module_name) # ModuleProxy
new_module.bind(module_real, proxies)
modules[module_name] = new_module
def register_prefs(*args: PrefProxy, **kwargs):
"""Registers preferences that should be handled by siteprefs.
Expects preferences as *args.
Use keyword arguments to batch apply params supported by
``PrefProxy`` to all preferences not constructed by ``pref`` and ``pref_group``.
Batch kwargs:
:param str help_text: Field help text.
:param bool static: Leave this preference static (do not store in DB).
:param bool readonly: Make this field read only.
:param bool swap_settings_module: Whether to automatically replace settings module
with a special ``ProxyModule`` object to access dynamic values of settings
transparently (so not to bother with calling ``.value`` of ``PrefProxy`` object).
"""
swap_settings_module = bool(kwargs.get('swap_settings_module', True))
if __PATCHED_LOCALS_SENTINEL not in get_frame_locals(2):
raise SitePrefsException('Please call `patch_locals()` right before the `register_prefs()`.')
bind_proxy(args, **kwargs)
unpatch_locals()
swap_settings_module and proxy_settings_module()
def pref_group(
title: str,
prefs: Union[List, Tuple],
help_text: str = '',
static: bool = True,
readonly: bool = False
):
"""Marks preferences group.
:param title: Group title
:param prefs: Preferences to group.
:param help_text: Field help text.
:param static: Leave this preference static (do not store in DB).
:param readonly: Make this field read only.
"""
bind_proxy(prefs, title, help_text=help_text, static=static, readonly=readonly)
for proxy in prefs: # For preferences already marked by pref().
if isinstance(proxy, PrefProxy):
proxy.category = title
def pref(
preference: Any,
field: Field = None,
verbose_name: str = None,
help_text: str = '',
static: bool = True,
readonly: bool = False
) -> Optional[PrefProxy]:
"""Marks a preference.
:param preference: Preference variable.
:param field: Django model field to represent this preference.
:param verbose_name: Field verbose name.
:param help_text: Field help text.
:param static: Leave this preference static (do not store in DB).
:param readonly: Make this field read only.
"""
try:
bound = bind_proxy(
(preference,),
field=field,
verbose_name=verbose_name,
help_text=help_text,
static=static,
readonly=readonly,
)
return bound[0]
except IndexError:
return
class preferences:
"""Context manager - main entry point for siteprefs.
.. code-block:: python
from siteprefs.toolbox import preferences
with preferences() as prefs:
prefs(
MY_OPTION_1,
prefs.one(MY_OPTION_2, static=False),
prefs.group('My Group', [prefs.one(MY_OPTION_42)]),
)
"""
one = staticmethod(pref)
group = staticmethod(pref_group)
__call__ = register_prefs
def __enter__(self):
patch_locals(3)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass