From ed5da75c00dac7d1121ac84c537e807176714cf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B4=9B=E6=B0=B4=E5=B1=85=E5=AE=A4?= Date: Sun, 31 Jul 2022 01:28:10 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20=E4=BE=9D=E8=B5=96=E6=B3=A8?= =?UTF-8?q?=E5=85=A5=E6=94=AF=E6=8C=81=E5=90=8C=E6=AD=A5=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E6=B3=A8=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/app/inject.py | 53 +++++++++++++++++++++++++++++---------------- 1 file changed, 34 insertions(+), 19 deletions(-) diff --git a/utils/app/inject.py b/utils/app/inject.py index a30e7c6..8ec0537 100644 --- a/utils/app/inject.py +++ b/utils/app/inject.py @@ -6,28 +6,43 @@ from model.types import Func from utils.app.manager import ServiceDict +def get_injections(func: Func): + injections = {} + try: + signature = inspect.signature(func) + except ValueError as exception: + if "no signature found" in str(exception): + Log.warning("no signature found", exception) + elif "not supported by signature" in str(exception): + Log.warning("not supported by signature", exception) + else: + raise exception + else: + for parameter_name, parameter in signature.parameters.items(): + annotation = parameter.annotation + class_name = annotation.__name__ + param = ServiceDict.get(class_name) + if param is not None: + injections.setdefault(parameter_name, param) + return injections + + def inject(func: Func) -> Func: """依赖注入""" @wraps(func) - async def decorator(*args, **kwargs): - try: - signature = inspect.signature(func) - except ValueError as exception: - if "no signature found" in str(exception): - Log.warning("no signature found", exception) - elif "not supported by signature" in str(exception): - Log.warning("not supported by signature", exception) - else: - raise exception - else: - for parameter_name, parameter in signature.parameters.items(): - annotation = parameter.annotation - class_name = annotation.__name__ - param = ServiceDict.get(class_name) - if param is not None: - kwargs.setdefault(parameter_name, param) - + 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