Skip to content

Commit 509e16d

Browse files
ababicAndy Babic
and
Andy Babic
authored
Search for pattern_contexts.py in python modules before looking up modifiers for a specific template (#147)
Co-authored-by: Andy Babic <[email protected]>
1 parent ebcc296 commit 509e16d

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

pattern_library/cm_utils.py

+23
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,30 @@
11

22
import inspect
3+
from importlib import import_module
34
from typing import Callable
45

6+
from django.apps import apps
7+
from django.utils.module_loading import module_has_submodule
8+
9+
10+
def get_app_modules():
11+
"""
12+
Generator function that yields a module object for each installed app
13+
yields tuples of (app_name, module)
14+
"""
15+
for app in apps.get_app_configs():
16+
yield app.name, app.module
17+
18+
19+
def get_app_submodules(submodule_name):
20+
"""
21+
Searches each app module for the specified submodule
22+
yields tuples of (app_name, module)
23+
"""
24+
for name, module in get_app_modules():
25+
if module_has_submodule(module, submodule_name):
26+
yield name, import_module('%s.%s' % (name, submodule_name))
27+
528

629
def accepts_kwarg(func: Callable, kwarg: str) -> bool:
730
"""

pattern_library/context_modifiers.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from django.core.exceptions import ImproperlyConfigured
66

7-
from .cm_utils import accepts_kwarg
7+
from .cm_utils import accepts_kwarg, get_app_submodules
88

99
GENERIC_CM_KEY = "__generic__"
1010
ORDER_ATTR_NAME = "__cm_order"
@@ -18,6 +18,12 @@
1818
class ContextModifierRegistry(defaultdict):
1919
def __init__(self):
2020
super().__init__(list)
21+
self.searched_for_modifiers = False
22+
23+
def search_for_modifiers(self) -> None:
24+
if not self.searched_for_modifiers:
25+
list(get_app_submodules('pattern_contexts'))
26+
self.searched_for_modifiers = True
2127

2228
def register(self, func: Callable, template: str = None, order: int = 0) -> None:
2329
"""
@@ -50,6 +56,7 @@ def register_decorator(self, func: Callable = None, **kwargs):
5056
return self.register(func, **kwargs)
5157

5258
def get_for_template(self, template: str):
59+
self.search_for_modifiers()
5360
modifiers = self[GENERIC_CM_KEY] + self[template]
5461
return sorted(modifiers, key=attrgetter(ORDER_ATTR_NAME))
5562

0 commit comments

Comments
 (0)