-
Notifications
You must be signed in to change notification settings - Fork 130
/
sitetreeapp.py
1194 lines (855 loc) · 39.4 KB
/
sitetreeapp.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
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
import warnings
from collections import defaultdict
from copy import deepcopy
from inspect import getfullargspec
from sys import exc_info
from threading import local
from typing import Callable, List, Optional, Dict, Union, Sequence, Any, Tuple
from django.conf import settings
from django.core.cache import caches
from django.db.models import signals, QuerySet
from django.template.base import (
FilterExpression, Lexer, Parser, Variable, VariableDoesNotExist, VARIABLE_TAG_START)
from django.template.context import Context
from django.template.loader import get_template
from django.urls import reverse, NoReverseMatch
from django.utils import module_loading
from django.utils.encoding import iri_to_uri
from django.utils.translation import get_language
from .compat import TOKEN_TEXT, TOKEN_VAR
from .exceptions import SiteTreeError
from .settings import (
ALIAS_TRUNK, ALIAS_THIS_CHILDREN, ALIAS_THIS_SIBLINGS, ALIAS_THIS_PARENT_SIBLINGS, ALIAS_THIS_ANCESTOR_CHILDREN,
UNRESOLVED_ITEM_MARKER, RAISE_ITEMS_ERRORS_ON_DEBUG, CACHE_TIMEOUT, CACHE_NAME, DYNAMIC_ONLY, ADMIN_APP_NAME,
SITETREE_CLS,
)
from .utils import get_tree_model, get_tree_item_model, import_app_sitetree_module, generate_id_for
if False: # pragma: nocover
from django.contrib.auth.models import User # noqa
from .models import TreeItemBase, TreeBase
TypeDynamicTrees = Dict[str, Union[Dict[str, List['TreeBase']], List['TreeBase']]]
TypeStrExpr = Union[str, FilterExpression]
MODEL_TREE_CLASS = get_tree_model()
MODEL_TREE_ITEM_CLASS = get_tree_item_model()
_ITEMS_PROCESSOR: Optional[Callable] = None
"""Stores tree items processor callable or None."""
_ITEMS_PROCESSOR_ARGS_LEN: int = 0
"""Number of arguments accepted by items processor."""
_I18N_TREES: List[str] = []
"""Stores aliases of trees supporting internationalization."""
_DYNAMIC_TREES: TypeDynamicTrees = {}
"""Holds trees dynamically loaded from project apps."""
_IDX_ORPHAN_TREES: str = 'orphans'
"""Dictionary index in `_DYNAMIC_TREES` for orphaned trees list."""
_IDX_TPL: str = '%s|:|%s'
"""Name template used as dictionary index in `_DYNAMIC_TREES`."""
_THREAD_LOCAL = local()
_THREAD_SITETREE: str = 'sitetree'
_UNSET = set() # Sentinel
cache = caches[CACHE_NAME]
def get_sitetree() -> 'SiteTree':
"""Returns SiteTree (thread-singleton) object, implementing utility methods.
This can return the built-in or a customized (see SITETREE_CLS setting) sitetree handler.
"""
sitetree = getattr(_THREAD_LOCAL, _THREAD_SITETREE, None)
if sitetree is None:
sitetree = _SITETREE_CLS()
setattr(_THREAD_LOCAL, _THREAD_SITETREE, sitetree)
return sitetree
def register_items_hook(func: Callable):
"""Registers a hook callable to process tree items right before they are passed to templates.
.. deprecated:: 1.13.0
Items hooking with `register_items_hook` is deprecated, please use `SITETREE_CLS`
setting customization instead and override .apply_hook() method.
Callable should be able to:
a) handle ``tree_items`` and ``tree_sender`` key params.
``tree_items`` will contain a list of extended TreeItem objects ready to pass to template.
``tree_sender`` will contain navigation type identifier
(e.g.: `menu`, `sitetree`, `breadcrumbs`, `menu.children`, `sitetree.children`)
b) return a list of extended TreeItems objects to pass to template.
Example::
# Put the following code somewhere where it'd be triggered as expected. E.g. in app view.py.
# First import the register function.
from sitetree.sitetreeapp import register_items_hook
# The following function will be used as items processor.
def my_items_processor(tree_items, tree_sender):
# Suppose we want to process only menu child items.
if tree_sender == 'menu.children':
# Lets add 'Hooked: ' to resolved titles of every item.
for item in tree_items:
item.title_resolved = f'Hooked: {item.title_resolved}'
# Return items list mutated or not.
return tree_items
# And we register items processor.
register_items_hook(my_items_processor)
:param func:
"""
warnings.warn(
'Items hooking with `register_items_hook` is deprecated, '
'please use `SITETREE_CLS` settings customization instead.',
DeprecationWarning, 2)
global _ITEMS_PROCESSOR
global _ITEMS_PROCESSOR_ARGS_LEN
_ITEMS_PROCESSOR = func
if func:
args_len = len(getfullargspec(func).args)
if args_len not in {2, 3}:
raise SiteTreeError('`register_items_hook()` expects a function with two or three arguments.')
_ITEMS_PROCESSOR_ARGS_LEN = args_len
def register_i18n_trees(aliases: List[str]):
"""Registers aliases of internationalized sitetrees.
Internationalized sitetrees are those, which are dubbed by other trees having
locale identifying suffixes in their aliases.
Lets suppose ``my_tree`` is the alias of a generic tree. This tree is the one
that we call by its alias in templates, and it is the one which is used
if no i18n version of that tree is found.
Given that ``my_tree_en``, ``my_tree_ru`` and other ``my_tree_{locale-id}``-like
trees are considered internationalization sitetrees. These are used (if available)
in accordance with current locale used by project.
Example::
# Put the following code somewhere where it'd be triggered as expected. E.g. in main urls.py.
# First import the register function.
from sitetree.sitetreeapp import register_i18n_trees
# At last we register i18n trees.
register_i18n_trees(['my_tree', 'my_another_tree'])
:param aliases:
"""
global _I18N_TREES
_I18N_TREES = aliases
def register_dynamic_trees(
trees: Union[List['TreeBase'], Dict[str, List['TreeBase']]],
*args,
**kwargs
):
"""Registers dynamic trees to be available for `sitetree` runtime.
Expects `trees` to be an iterable with structures created with `compose_dynamic_tree()`.
Example::
register_dynamic_trees(
# Get all the trees from `my_app`.
compose_dynamic_tree('my_app'),
# Get all the trees from `my_app` and attach them to `main` tree root.
compose_dynamic_tree('my_app', target_tree_alias='main'),
# Get all the trees from `my_app` and attach them to `has_dynamic` aliased item in `main` tree.
compose_dynamic_tree('articles', target_tree_alias='main', parent_tree_item_alias='has_dynamic'),
# Define a tree right on the registration.
compose_dynamic_tree((
tree('dynamic', items=(
item('dynamic_1', 'dynamic_1_url', children=(
item('dynamic_1_sub_1', 'dynamic_1_sub_1_url'),
)),
item('dynamic_2', 'dynamic_2_url'),
)),
)),
)
Accepted kwargs:
bool reset_cache: Resets tree cache, to introduce all changes made to a tree immediately.
"""
global _DYNAMIC_TREES
if _IDX_ORPHAN_TREES not in _DYNAMIC_TREES:
_DYNAMIC_TREES[_IDX_ORPHAN_TREES] = {}
if isinstance(trees, dict): # New `less-brackets` style registration.
trees = [trees]
trees.extend(args)
for tree in trees or []:
if tree is not None and tree['sitetrees'] is not None:
if tree['tree'] is None:
# Register trees as they are defined in app.
for st in tree['sitetrees']:
if st.alias not in _DYNAMIC_TREES[_IDX_ORPHAN_TREES]:
_DYNAMIC_TREES[_IDX_ORPHAN_TREES][st.alias] = []
_DYNAMIC_TREES[_IDX_ORPHAN_TREES][st.alias].append(st)
else:
# Register tree items as parts of existing trees.
index = _IDX_TPL % (tree['tree'], tree['parent_item'])
if index not in _DYNAMIC_TREES:
_DYNAMIC_TREES[index] = []
_DYNAMIC_TREES[index].extend(tree['sitetrees'])
reset_cache = kwargs.get('reset_cache', False)
if reset_cache:
cache_ = get_sitetree().cache
cache_.empty()
cache_.reset()
def get_dynamic_trees() -> TypeDynamicTrees:
"""Returns a dictionary with currently registered dynamic trees."""
return _DYNAMIC_TREES
def compose_dynamic_tree(
src: Union[str, Sequence['TreeBase'], Sequence['TreeItemBase']],
target_tree_alias: str = None,
parent_tree_item_alias: str = None,
include_trees: List[str] = None
) -> dict:
"""Returns a structure describing a dynamic sitetree.utils
The structure can be built from various sources,
:param src: If a string is passed to `src`, it'll be treated as the name of an app,
from where one want to import sitetrees definitions. `src` can be an iterable
of tree definitions (see `sitetree.toolbox.tree()` and `item()` functions).
:param target_tree_alias: Static tree alias to attach items from dynamic trees to.
:param parent_tree_item_alias: Tree item alias from a static tree to attach items from dynamic trees to.
:param include_trees: Sitetree aliases to filter `src`.
"""
def result(sitetrees):
if include_trees is not None:
sitetrees = [tree for tree in sitetrees if tree.alias in include_trees]
return {
'app': src,
'sitetrees': sitetrees,
'tree': target_tree_alias,
'parent_item': parent_tree_item_alias}
if isinstance(src, str):
# Considered to be an application name.
try:
module = import_app_sitetree_module(src)
return None if module is None else result(getattr(module, 'sitetrees', None))
except ImportError as e:
if settings.DEBUG:
warnings.warn(f'Unable to register dynamic sitetree(s) for `{src}` application: {e}. ')
return {}
return result(src)
class LazyTitle:
"""Lazily resolves any variable found in a title of an item.
Produces resolved title as unicode representation.
"""
def __init__(self, title: str):
self.title = title
def __str__(self):
my_lexer = Lexer(self.title)
my_tokens = my_lexer.tokenize()
# Deliberately strip off template tokens that are not text or variable.
for my_token in my_tokens:
if my_token.token_type not in (TOKEN_TEXT, TOKEN_VAR):
my_tokens.remove(my_token)
my_parser = Parser(my_tokens)
return my_parser.parse().render(get_sitetree().current_page_context)
def __eq__(self, other):
return self.__str__() == other
class Cache:
"""Contains cache-related stuff."""
def __init__(self):
self.cache: dict = {}
cache_empty = self.empty
# Listen for signals from the models.
signals.post_save.connect(cache_empty, sender=MODEL_TREE_CLASS)
signals.post_save.connect(cache_empty, sender=MODEL_TREE_ITEM_CLASS)
signals.post_delete.connect(cache_empty, sender=MODEL_TREE_ITEM_CLASS)
# Listen to the changes in item permissions table.
signals.m2m_changed.connect(cache_empty, sender=MODEL_TREE_ITEM_CLASS.access_permissions)
self.init()
@classmethod
def reset(cls):
"""Instructs sitetree to drop and recreate cache.
Could be used to show up tree changes made in a different process.
"""
cache.set('sitetrees_reset', True)
def init(self):
"""Initializes local cache from Django cache."""
# Drop cache flag set by .reset() method.
cache.get('sitetrees_reset') and self.empty(init=False)
self.cache = cache.get(
'sitetrees', {'sitetrees': {}, 'parents': {}, 'items_by_ids': {}, 'tree_aliases': {}})
def save(self):
"""Saves sitetree data to Django cache."""
cache.set('sitetrees', self.cache, CACHE_TIMEOUT)
def empty(self, **kwargs):
"""Empties cached sitetree data."""
cache.delete('sitetrees')
cache.delete('sitetrees_reset')
kwargs.get('init', True) and self.init()
def get_entry(self, entry_name: str, key) -> Any:
"""Returns cache entry parameter value by its name.
:param entry_name:
:param key:
"""
return self.cache[entry_name].get(key, False)
def update_entry_value(self, entry_name: str, key: str, value: Any):
"""Updates cache entry parameter with new data.
:param entry_name:
:param key:
:param value:
"""
if key not in self.cache[entry_name]:
self.cache[entry_name][key] = {}
self.cache[entry_name][key].update(value)
def set_entry(self, entry_name: str, key: str, value: Any):
"""Replaces entire cache entry parameter data by its name with new data.
:param entry_name:
:param key:
:param value:
"""
self.cache[entry_name][key] = value
class SiteTree:
"""Main logic handler."""
cache_cls = Cache # Allow customizations.
def __init__(self):
self.init(context=None)
def init(self, context: Optional[Context]):
"""Initializes sitetree to handle new request.
:param context:
"""
self.cache = self.cache_cls()
self.current_page_context = context
self.current_lang = get_language()
request = context.get('request', None) if context else None
self.current_request = request
current_app = (
getattr(request, 'current_app', None) or
getattr(getattr(request, 'resolver_match', None), 'namespace', None) or
(context or {}).get('current_app', '') # May be set by TreeItemChoiceField.
)
self._current_app_is_admin = current_app == ADMIN_APP_NAME
self._current_app = current_app
self._current_user_permissions = _UNSET
self._items_urls = {} # Resolved urls are cache for a request.
self._current_items = {}
def resolve_tree_i18n_alias(self, alias: str) -> str:
"""Resolves internationalized tree alias.
Verifies whether a separate sitetree is available for currently active language.
If so, returns i18n alias. If not, returns the initial alias.
:param alias:
"""
if alias not in _I18N_TREES:
return alias
current_language_code = self.current_lang
i18n_tree_alias = f'{alias}_{current_language_code}'
trees_count = self.cache.get_entry('tree_aliases', i18n_tree_alias)
if trees_count is False:
trees_count = MODEL_TREE_CLASS.objects.filter(alias=i18n_tree_alias).count()
self.cache.set_entry('tree_aliases', i18n_tree_alias, trees_count)
if trees_count:
alias = i18n_tree_alias
return alias
@staticmethod
def attach_dynamic_tree_items(
tree_alias: str,
src_tree_items: Union[Sequence['TreeItemBase'], QuerySet]
) -> List['TreeItemBase']:
"""Attaches dynamic sitetrees items registered with `register_dynamic_trees()`
to an initial (source) items list.
:param tree_alias:
:param src_tree_items:
"""
if not _DYNAMIC_TREES:
return list(src_tree_items)
# This guarantees that a dynamic source stays intact,
# no matter how dynamic sitetrees are attached.
trees = deepcopy(_DYNAMIC_TREES)
items = []
if not src_tree_items:
if _IDX_ORPHAN_TREES in trees and tree_alias in trees[_IDX_ORPHAN_TREES]:
for tree in trees[_IDX_ORPHAN_TREES][tree_alias]:
items.extend(tree.dynamic_items)
else:
# TODO Seems to be underoptimized %)
# Tree item attachment by alias.
for static_item in list(src_tree_items):
items.append(static_item)
if not static_item.alias:
continue
idx = _IDX_TPL % (tree_alias, static_item.alias)
if idx not in trees:
continue
for tree in trees[idx]:
tree.alias = tree_alias
for dyn_item in tree.dynamic_items: # noqa dynamic attr
if dyn_item.parent is None:
dyn_item.parent = static_item
# Unique IDs are required for the same trees attached
# to different parents.
dyn_item.id = generate_id_for(dyn_item)
items.append(dyn_item)
# Tree root attachment.
idx = _IDX_TPL % (tree_alias, None)
if idx in _DYNAMIC_TREES:
trees = deepcopy(_DYNAMIC_TREES)
for tree in trees[idx]:
tree.alias = tree_alias
items.extend(tree.dynamic_items) # noqa dynamic attr
return items
def current_app_is_admin(self) -> bool:
"""Returns boolean whether current application is Admin contrib."""
warnings.warn(
'Accessing .current_app_is_admin() is deprecated.',
DeprecationWarning, 2)
return self._current_app_is_admin
def get_sitetree(self, alias: str) -> Tuple[str, List['TreeItemBase']]:
"""Gets site tree items from the given site tree.
Caches result to dictionary.
Returns (tree alias, tree items) tuple.
:param alias:
"""
cache_ = self.cache
get_cache_entry = cache_.get_entry
set_cache_entry = cache_.set_entry
caching_required = False
if not self._current_app_is_admin:
# We do not need i18n for a tree rendered in Admin dropdown.
alias = self.resolve_tree_i18n_alias(alias)
sitetree = get_cache_entry('sitetrees', alias)
if not sitetree:
if DYNAMIC_ONLY:
sitetree = []
else:
sitetree = (
MODEL_TREE_ITEM_CLASS.objects.
select_related('parent', 'tree').
prefetch_related('access_permissions__content_type').
filter(tree__alias__exact=alias).
order_by('parent__sort_order', 'sort_order'))
sitetree = self.attach_dynamic_tree_items(alias, sitetree)
set_cache_entry('sitetrees', alias, sitetree)
caching_required = True
parents = get_cache_entry('parents', alias)
if not parents:
parents = defaultdict(list)
for item in sitetree:
parent = getattr(item, 'parent')
parents[parent].append(item)
set_cache_entry('parents', alias, parents)
# Prepare items by ids cache if needed.
if caching_required:
# We need this extra pass to avoid future problems on items depth calculation.
cache_update = cache_.update_entry_value
for item in sitetree:
cache_update('items_by_ids', alias, {item.id: item})
url = self.url
calculate_item_depth = self.calculate_item_depth
for item in sitetree:
if caching_required:
item.has_children = False
if not hasattr(item, 'depth'):
item.depth = calculate_item_depth(alias, item.id)
item.depth_range = range(item.depth)
# Resolve item permissions.
if item.access_restricted:
permissions_src = (
item.permissions if getattr(item, 'is_dynamic', False)
else item.access_permissions.all())
item.perms = set(
[f'{perm.content_type.app_label}.{perm.codename}' for perm in permissions_src])
# Contextual properties.
item.url_resolved = url(item)
item.title_resolved = LazyTitle(item.title) if VARIABLE_TAG_START in item.title else item.title
item.is_current = False
item.in_current_branch = False
# Get current item for the given sitetree.
self.get_tree_current_item(alias)
# Save sitetree data into cache if needed.
if caching_required:
cache_.save()
return alias, sitetree
def calculate_item_depth(self, tree_alias: str, item_id: int, depth: int = 0):
"""Calculates depth of the item in the tree.
:param tree_alias:
:param item_id:
:param depth:
"""
item = self.get_item_by_id(tree_alias, item_id)
if hasattr(item, 'depth'):
depth = item.depth + depth
else:
if item.parent is not None:
depth = self.calculate_item_depth(tree_alias, item.parent.id, depth + 1)
return depth
def get_item_by_id(self, tree_alias: str, item_id: int) -> 'TreeItemBase':
"""Get the item from the tree by its ID.
:param tree_alias:
:param item_id:
"""
return self.cache.get_entry('items_by_ids', tree_alias)[item_id]
def get_tree_current_item(self, tree_alias: str) -> Optional['TreeItemBase']:
"""Resolves current tree item of 'tree_alias' tree matching current
request path against URL of given tree item.
:param tree_alias:
"""
current_item = self._current_items.get(tree_alias, _UNSET)
if current_item is not _UNSET:
if current_item is not None:
current_item.is_current = True # Could be reset by .get_sitetree()
return current_item # noqa
current_item = None
if self._current_app_is_admin:
self._current_items[tree_alias] = current_item
return None
current_url = self.current_request.path
if current_url:
# url quote is an attempt to support non-ascii in url.
current_url = iri_to_uri(current_url)
for url_item, url in self._items_urls.items():
# Iterate each as this dict may contains "current" items for various trees.
if url != current_url:
continue
url_item.is_current = True
if url_item.tree.alias == tree_alias:
current_item = url_item
if current_item is not None:
self._current_items[tree_alias] = current_item
return current_item
def url(self, sitetree_item: Union['TreeItemBase', FilterExpression], context: Context = None) -> str:
"""Resolves item's URL.
:param sitetree_item: TreeItemBase heir object, 'url' property of which
is processed as URL pattern or simple URL.
:param context:
"""
context = context or self.current_page_context
resolve_var = self.resolve_var
if not isinstance(sitetree_item, MODEL_TREE_ITEM_CLASS):
sitetree_item = resolve_var(sitetree_item, context)
resolved_url = self._items_urls.get(sitetree_item)
if resolved_url is not None:
return resolved_url
# Resolve only if item's URL is marked as pattern.
if sitetree_item.urlaspattern:
url = sitetree_item.url
view_path = url
all_arguments = []
if ' ' in url:
view_path = url.split(' ')
# We should try to resolve URL parameters from site tree item.
for view_argument in view_path[1:]:
all_arguments.append(resolve_var(view_argument))
view_path = view_path[0].strip('"\' ')
try:
resolved_url = reverse(
view_path,
args=all_arguments,
current_app=self._current_app
)
except NoReverseMatch:
resolved_url = UNRESOLVED_ITEM_MARKER
else:
resolved_url = f'{sitetree_item.url}'
self._items_urls[sitetree_item] = resolved_url
return resolved_url
def init_tree(
self,
tree_alias: str,
context: Context
) -> Tuple[Optional[str], Optional[List['TreeItemBase']]]:
"""Initializes sitetree in memory.
Returns tuple with resolved tree alias and items on success.
On fail returns (None, None).
:param tree_alias:
:param context:
"""
request = context.get('request', None)
if request is None:
if any(exc_info()):
# Probably we're in a technical
# exception handling view. So we won't mask
# the initial exception with the one below.
return None, None
raise SiteTreeError(
'Sitetree requires "django.core.context_processors.request" template context processor to be active. '
'If it is, check that your view pushes request data into the template.')
if id(request) != id(self.current_request):
self.init(context)
# Resolve tree_alias from the context.
tree_alias = self.resolve_var(tree_alias)
tree_alias, sitetree_items = self.get_sitetree(tree_alias)
if not sitetree_items:
return None, None
return tree_alias, sitetree_items
def get_current_page_title(self, tree_alias: TypeStrExpr, context: Context) -> str:
"""Returns resolved from sitetree title for current page.
:param tree_alias:
:param context:
"""
return self.get_current_page_attr('title_resolved', tree_alias, context)
def get_current_page_attr(self, attr_name: str, tree_alias: TypeStrExpr, context: Context) -> str:
"""Returns an arbitrary attribute of a sitetree item resolved as current for current page.
:param attr_name:
:param tree_alias:
:param context:
"""
tree_alias, sitetree_items = self.init_tree(tree_alias, context)
current_item = self.get_tree_current_item(tree_alias)
if current_item is None:
if settings.DEBUG and RAISE_ITEMS_ERRORS_ON_DEBUG:
raise SiteTreeError(
f'Unable to resolve current sitetree item to get a `{attr_name}` for current page. Check whether '
'there is an appropriate sitetree item defined for current URL.')
return ''
return getattr(current_item, attr_name, '')
def get_ancestor_level(self, current_item: 'TreeItemBase', depth: int = 1) -> 'TreeItemBase':
"""Returns ancestor of level `deep` recursively
:param current_item:
:param depth:
"""
if current_item.parent is None:
return current_item
if depth <= 1:
return current_item.parent
return self.get_ancestor_level(current_item.parent, depth=depth-1)
def menu(self, tree_alias: TypeStrExpr, tree_branches: TypeStrExpr, context: Context) -> List['TreeItemBase']:
"""Builds and returns menu structure for 'sitetree_menu' tag.
:param tree_alias:
:param tree_branches:
:param context:
"""
tree_alias, sitetree_items = self.init_tree(tree_alias, context)
if not sitetree_items:
return []
tree_branches = self.resolve_var(tree_branches)
parent_isnull = False
parent_ids = []
parent_aliases = []
current_item = self.get_tree_current_item(tree_alias)
self.tree_climber(tree_alias, current_item)
# Support item addressing both through identifiers and aliases.
for branch_id in tree_branches.split(','):
branch_id = branch_id.strip()
if branch_id == ALIAS_TRUNK:
parent_isnull = True
elif branch_id == ALIAS_THIS_CHILDREN and current_item is not None:
branch_id = current_item.id
parent_ids.append(branch_id)
elif branch_id == ALIAS_THIS_ANCESTOR_CHILDREN and current_item is not None:
branch_id = self.get_ancestor_item(tree_alias, current_item).id
parent_ids.append(branch_id)
elif branch_id == ALIAS_THIS_SIBLINGS and current_item is not None and current_item.parent is not None:
branch_id = current_item.parent.id
parent_ids.append(branch_id)
elif branch_id == ALIAS_THIS_PARENT_SIBLINGS and current_item is not None:
branch_id = self.get_ancestor_level(current_item, depth=2).id
parent_ids.append(branch_id)
elif branch_id.isdigit():
parent_ids.append(int(branch_id))
else:
parent_aliases.append(branch_id)
check_access = self.check_access
menu_items = []
for item in sitetree_items:
if not item.hidden and item.inmenu and check_access(item, context):
if item.parent is None:
if parent_isnull:
menu_items.append(item)
else:
if item.parent.id in parent_ids or item.parent.alias in parent_aliases:
menu_items.append(item)
menu_items = self.apply_hook(menu_items, 'menu')
self.update_has_children(tree_alias, menu_items, 'menu')
return menu_items
def apply_hook(self, items: List['TreeItemBase'], sender: str) -> List['TreeItemBase']:
"""Applies a custom items processing hook to items supplied, and returns processed list.
Suitable for items filtering and other manipulations.
Returns initial items list if no hook is registered.
.. note:: Use `SITETREE_CLS` setting customization and override this method.
:param items:
:param sender: menu, breadcrumbs, sitetree, {type}.children, {type}.has_children
"""
processor = _ITEMS_PROCESSOR
if processor is None:
return items
if _ITEMS_PROCESSOR_ARGS_LEN == 2:
return processor(tree_items=items, tree_sender=sender)
return processor(tree_items=items, tree_sender=sender, context=self.current_page_context)
def check_access_auth(self, item: 'TreeItemBase', context: Context) -> bool:
"""Performs authentication related checks: whether the current user has an access to a certain item.
:param item:
:param context:
"""
authenticated = self.current_request.user.is_authenticated
if hasattr(authenticated, '__call__'):
authenticated = authenticated()
if item.access_loggedin and not authenticated:
return False
if item.access_guest and authenticated:
return False
return True
def check_access_perms(self, item: 'TreeItemBase', context: Context) -> bool:
"""Performs permissions related checks: whether the current user has an access to a certain item.
:param item:
:param context:
"""
if item.access_restricted:
user_perms = self._current_user_permissions
if user_perms is _UNSET:
user_perms = self.get_permissions(self.current_request.user, item)
self._current_user_permissions = user_perms
perms = item.perms # noqa dynamic attr
if item.access_perm_type == MODEL_TREE_ITEM_CLASS.PERM_TYPE_ALL:
if len(perms) != len(perms.intersection(user_perms)):
return False
else:
if not len(perms.intersection(user_perms)):
return False
return True
def check_access_dyn(self, item: 'TreeItemBase', context: Context) -> Optional[bool]:
"""Performs dynamic item access check.
:param item: The item is expected to have `access_check` callable attribute implementing the check.
:param context:
"""
result = None
access_check_func = getattr(item, 'access_check', None)
if access_check_func:
return access_check_func(tree=self)
return None
def check_access(self, item: 'TreeItemBase', context: Context) -> bool:
"""Checks whether a current user has an access to a certain item.
:param item:
:param context:
"""
dyn_check = self.check_access_dyn(item, context)
if dyn_check is not None:
return dyn_check
if not self.check_access_auth(item, context):
return False
if not self.check_access_perms(item, context):
return False
return True
def get_permissions(self, user: 'User', item: 'TreeItemBase') -> set:
"""Returns a set of user and group level permissions for a given user.
:param user:
:param item:
"""
return user.get_all_permissions()
def breadcrumbs(self, tree_alias: TypeStrExpr, context: Context) -> List['TreeItemBase']:
"""Builds and returns breadcrumb trail structure for 'sitetree_breadcrumbs' tag.
:param tree_alias:
:param context:
"""
tree_alias, sitetree_items = self.init_tree(tree_alias, context)
if not sitetree_items:
return []
current_item = self.get_tree_current_item(tree_alias)
breadcrumbs = []
if current_item is not None:
context_ = self.current_page_context
check_access = self.check_access
get_item_by_id = self.get_item_by_id