Skip to content

Commit ed4e905

Browse files
committed
Removed unnecessary action on module building process and Added ModuleExecution context
1 parent f95930e commit ed4e905

File tree

8 files changed

+311
-179
lines changed

8 files changed

+311
-179
lines changed

ellar/core/modules/base.py

Lines changed: 97 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,118 @@
11
import typing as t
22

3-
from ellar.common.constants import MODULE_FIELDS
3+
from ellar.common.compatible import AttributeDict
4+
from ellar.common.constants import (
5+
APP_EXCEPTION_HANDLERS_KEY,
6+
APP_MIDDLEWARE_HANDLERS_KEY,
7+
EXCEPTION_HANDLERS_KEY,
8+
MIDDLEWARE_HANDLERS_KEY,
9+
MODULE_DECORATOR_ITEM,
10+
TEMPLATE_CONTEXT_PROCESSOR_KEY,
11+
TEMPLATE_FILTER_KEY,
12+
TEMPLATE_GLOBAL_KEY,
13+
)
14+
from ellar.common.exceptions import CallableExceptionHandler
15+
from ellar.core.middleware import FunctionBasedMiddleware
16+
from ellar.core.middleware.middleware import EllarMiddleware
17+
from ellar.core.modules.helper import module_callable_factory
418
from ellar.di.injector import Container
19+
from ellar.reflect import reflect
20+
from ellar.utils import get_functions_with_tag
521
from injector import Binder
622
from injector import Module as _InjectorModule
723

8-
from .builder import ModuleBaseBuilder
9-
1024
if t.TYPE_CHECKING: # pragma: no cover
11-
from ellar.core.conf import Config
25+
from ellar.common.templating import TemplateFunctionData
26+
from ellar.core.modules import ModuleRefBase
1227

1328

14-
class ModuleBaseMeta(type):
15-
MODULE_FIELDS: t.Dict = {}
29+
class _ModuleBaseBuilder:
30+
__slots__ = ("_cls", "_actions")
31+
32+
def __init__(self, cls: t.Union[t.Type["ModuleBase"], "ModuleBaseMeta"]) -> None:
33+
self._cls = cls
34+
self._actions: t.Dict[str, t.Callable[[t.Any], None]] = {
35+
EXCEPTION_HANDLERS_KEY: self.exception_config,
36+
MIDDLEWARE_HANDLERS_KEY: self.middleware_config,
37+
TEMPLATE_GLOBAL_KEY: self.template_global_config,
38+
TEMPLATE_FILTER_KEY: self.template_filter_config,
39+
TEMPLATE_CONTEXT_PROCESSOR_KEY: self.template_context_processor,
40+
}
41+
42+
def exception_config(self, exception_dict: t.Dict) -> None:
43+
for k, v in exception_dict.items():
44+
func, global_exc = v
45+
reflect.define_metadata(
46+
APP_EXCEPTION_HANDLERS_KEY if global_exc else EXCEPTION_HANDLERS_KEY,
47+
[
48+
CallableExceptionHandler(
49+
handler=module_callable_factory(func, self._cls),
50+
exc_or_status_code=k,
51+
)
52+
],
53+
self._cls,
54+
)
55+
56+
@t.no_type_check
57+
def middleware_config(self, middleware: AttributeDict) -> None:
58+
dispatch = module_callable_factory(middleware.dispatch, self._cls)
59+
reflect.define_metadata(
60+
APP_MIDDLEWARE_HANDLERS_KEY
61+
if middleware.is_global
62+
else MIDDLEWARE_HANDLERS_KEY,
63+
[
64+
EllarMiddleware(
65+
FunctionBasedMiddleware,
66+
dispatch=dispatch,
67+
**middleware.options,
68+
)
69+
],
70+
self._cls,
71+
)
1672

17-
def build_module_actions(cls) -> None:
18-
ModuleBaseBuilder(cls).build()
73+
def template_filter_config(self, template_filter: "TemplateFunctionData") -> None:
74+
reflect.define_metadata(
75+
TEMPLATE_FILTER_KEY,
76+
{
77+
template_filter.name: module_callable_factory(
78+
template_filter.func, self._cls
79+
)
80+
},
81+
self._cls,
82+
)
1983

84+
def template_context_processor(self, f: t.Callable) -> None:
85+
reflect.define_metadata(TEMPLATE_CONTEXT_PROCESSOR_KEY, [f], self._cls)
86+
87+
def template_global_config(self, template_filter: "TemplateFunctionData") -> None:
88+
reflect.define_metadata(
89+
TEMPLATE_GLOBAL_KEY,
90+
{
91+
template_filter.name: module_callable_factory(
92+
template_filter.func, self._cls
93+
)
94+
},
95+
self._cls,
96+
)
97+
98+
def build(self) -> None:
99+
for _, item in get_functions_with_tag(self._cls, MODULE_DECORATOR_ITEM):
100+
action_name = getattr(item, MODULE_DECORATOR_ITEM)
101+
handler = self._actions[action_name]
102+
handler(item.__dict__[action_name])
103+
104+
105+
class ModuleBaseMeta(type):
20106
@t.no_type_check
21107
def __init__(cls, name, bases, namespace) -> None:
22108
super().__init__(name, bases, namespace)
23-
setattr(cls, MODULE_FIELDS, {})
24-
25-
# for base in reversed(bases):
26-
# ModuleBaseBuilder(cls).build(getattr(base, MODULE_FIELDS, base.__dict__))
27-
# ModuleBaseBuilder(cls).build(namespace)
109+
_ModuleBaseBuilder(cls).build()
28110

29111

30112
class ModuleBase(_InjectorModule, metaclass=ModuleBaseMeta):
31113
@classmethod
32-
def before_init(cls, config: "Config") -> t.Dict:
33-
"""Before Module initialisation. Whatever value that is returned here will be passed
34-
to the Module constructor during initialisation"""
35-
return {}
114+
def post_build(cls, module_ref: "ModuleRefBase") -> None:
115+
"""Executed after a Subclass build process is done"""
36116

37117
def register_services(self, container: Container) -> None:
38118
"""Register other services manually"""

ellar/core/modules/builder.py

Lines changed: 0 additions & 84 deletions
This file was deleted.

ellar/core/modules/config.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ class DynamicModule:
4646
commands: t.Sequence[t.Union[click.Command, click.Group, t.Any]] = (
4747
dataclasses.field(default_factory=lambda: ())
4848
)
49+
4950
exports: t.List[t.Union[t.Type, t.Any]] = dataclasses.field(
5051
default_factory=lambda: []
5152
)
@@ -269,7 +270,7 @@ def get_module_dependency_by_name(
269270
tree_manager.find_module(lambda data: data.name == self.module_name)
270271
)
271272

272-
if not node:
273+
if node is None:
273274
raise ImproperConfiguration(
274275
f"ForwardRefModule module_name='{self.module_name}' "
275276
f"defined in {parent_module_ref.module} could not be found.\n"
@@ -295,7 +296,7 @@ def get_module_dependency_by_type(
295296

296297
node = tree_manager.get_module(module_cls)
297298

298-
if not node:
299+
if node is None:
299300
raise ImproperConfiguration(
300301
f"ForwardRefModule module='{self.module}' "
301302
f"defined in {parent_module_ref.module} could not be found.\n"

ellar/core/modules/helper.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@
66

77

88
def _executor_wrapper_async(
9-
cls: t.Type,
10-
func: t.Callable,
9+
cls: t.Type, func: t.Callable
1110
) -> t.Callable[..., t.Coroutine]:
1211
@wraps(func)
1312
async def _decorator(*args: t.Any, **kwargs: t.Any) -> t.Any:

0 commit comments

Comments
 (0)