Skip to content

Commit 74e1c6c

Browse files
author
Andy Babic
committed
Search for context_modifiers.py in python modules before looking up modifiers for a specific template
1 parent ebcc296 commit 74e1c6c

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

pattern_library/cm_utils.py

Lines changed: 23 additions & 0 deletions
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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
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
8+
89

910
GENERIC_CM_KEY = "__generic__"
1011
ORDER_ATTR_NAME = "__cm_order"
@@ -18,6 +19,12 @@
1819
class ContextModifierRegistry(defaultdict):
1920
def __init__(self):
2021
super().__init__(list)
22+
self.searched_for_modifiers = False
23+
24+
def search_for_modifiers(self) -> None:
25+
if not self.searched_for_modifiers:
26+
list(get_app_submodules('context_modifiers'))
27+
self.searched_for_modifiers = True
2128

2229
def register(self, func: Callable, template: str = None, order: int = 0) -> None:
2330
"""
@@ -50,6 +57,7 @@ def register_decorator(self, func: Callable = None, **kwargs):
5057
return self.register(func, **kwargs)
5158

5259
def get_for_template(self, template: str):
60+
self.search_for_modifiers()
5361
modifiers = self[GENERIC_CM_KEY] + self[template]
5462
return sorted(modifiers, key=attrgetter(ORDER_ATTR_NAME))
5563

0 commit comments

Comments
 (0)