mirror of
https://github.com/PaiGramTeam/PamGram.git
synced 2024-11-22 06:17:54 +00:00
🔧 依赖注入支持同步函数注入
This commit is contained in:
parent
b70e50133b
commit
ed5da75c00
@ -6,11 +6,8 @@ from model.types import Func
|
||||
from utils.app.manager import ServiceDict
|
||||
|
||||
|
||||
def inject(func: Func) -> Func:
|
||||
"""依赖注入"""
|
||||
|
||||
@wraps(func)
|
||||
async def decorator(*args, **kwargs):
|
||||
def get_injections(func: Func):
|
||||
injections = {}
|
||||
try:
|
||||
signature = inspect.signature(func)
|
||||
except ValueError as exception:
|
||||
@ -26,8 +23,26 @@ def inject(func: Func) -> Func:
|
||||
class_name = annotation.__name__
|
||||
param = ServiceDict.get(class_name)
|
||||
if param is not None:
|
||||
kwargs.setdefault(parameter_name, param)
|
||||
injections.setdefault(parameter_name, param)
|
||||
return injections
|
||||
|
||||
|
||||
def inject(func: Func) -> Func:
|
||||
"""依赖注入"""
|
||||
|
||||
@wraps(func)
|
||||
async def async_decorator(*args, **kwargs):
|
||||
injections = get_injections(func)
|
||||
kwargs.update(injections)
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
return decorator
|
||||
@wraps(func)
|
||||
def sync_decorator(*args, **kwargs):
|
||||
injections = get_injections(func)
|
||||
kwargs.update(injections)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
if inspect.iscoroutinefunction(func):
|
||||
return async_decorator
|
||||
else:
|
||||
return sync_decorator
|
||||
|
Loading…
Reference in New Issue
Block a user