2022-01-22 15:23:07 +08:00
|
|
|
|
"""本模块模块实现了依赖注入的定义与处理。
|
|
|
|
|
|
|
|
|
|
FrontMatter:
|
|
|
|
|
sidebar_position: 0
|
|
|
|
|
description: nonebot.dependencies 模块
|
|
|
|
|
"""
|
2021-11-16 18:30:16 +08:00
|
|
|
|
|
2021-12-12 18:19:08 +08:00
|
|
|
|
import abc
|
2022-09-07 09:59:05 +08:00
|
|
|
|
import asyncio
|
2021-11-12 20:55:59 +08:00
|
|
|
|
import inspect
|
2022-09-07 09:59:05 +08:00
|
|
|
|
from dataclasses import field, dataclass
|
2022-08-14 19:41:00 +08:00
|
|
|
|
from typing import (
|
|
|
|
|
Any,
|
|
|
|
|
Dict,
|
|
|
|
|
List,
|
|
|
|
|
Type,
|
2022-09-07 09:59:05 +08:00
|
|
|
|
Tuple,
|
2022-08-14 19:41:00 +08:00
|
|
|
|
Generic,
|
|
|
|
|
TypeVar,
|
|
|
|
|
Callable,
|
2022-09-07 09:59:05 +08:00
|
|
|
|
Iterable,
|
2022-08-14 19:41:00 +08:00
|
|
|
|
Optional,
|
|
|
|
|
Awaitable,
|
|
|
|
|
cast,
|
|
|
|
|
)
|
2021-11-12 20:55:59 +08:00
|
|
|
|
|
2021-11-14 18:51:23 +08:00
|
|
|
|
from nonebot.log import logger
|
2022-08-14 19:41:00 +08:00
|
|
|
|
from nonebot.typing import _DependentCallable
|
2022-09-09 11:52:57 +08:00
|
|
|
|
from nonebot.exception import SkippedException
|
2021-12-12 18:19:08 +08:00
|
|
|
|
from nonebot.utils import run_sync, is_coroutine_callable
|
2024-01-26 11:12:57 +08:00
|
|
|
|
from nonebot.compat import FieldInfo, ModelField, PydanticUndefined
|
2021-11-21 15:46:48 +08:00
|
|
|
|
|
2022-01-28 14:49:04 +08:00
|
|
|
|
from .utils import check_field_type, get_typed_signature
|
2022-01-15 21:27:43 +08:00
|
|
|
|
|
2021-12-12 18:19:08 +08:00
|
|
|
|
R = TypeVar("R")
|
2022-01-28 14:49:04 +08:00
|
|
|
|
T = TypeVar("T", bound="Dependent")
|
2021-11-12 20:55:59 +08:00
|
|
|
|
|
|
|
|
|
|
2021-12-12 18:19:08 +08:00
|
|
|
|
class Param(abc.ABC, FieldInfo):
|
2022-01-21 21:04:17 +08:00
|
|
|
|
"""依赖注入的基本单元 —— 参数。
|
|
|
|
|
|
|
|
|
|
继承自 `pydantic.fields.FieldInfo`,用于描述参数信息(不包括参数名)。
|
|
|
|
|
"""
|
|
|
|
|
|
2023-08-29 18:45:12 +08:00
|
|
|
|
def __init__(self, *args, validate: bool = False, **kwargs: Any) -> None:
|
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
self.validate = validate
|
|
|
|
|
|
2021-12-12 18:19:08 +08:00
|
|
|
|
@classmethod
|
|
|
|
|
def _check_param(
|
2022-09-07 09:59:05 +08:00
|
|
|
|
cls, param: inspect.Parameter, allow_types: Tuple[Type["Param"], ...]
|
2021-12-12 18:19:08 +08:00
|
|
|
|
) -> Optional["Param"]:
|
2022-09-07 09:59:05 +08:00
|
|
|
|
return
|
2021-11-16 18:30:16 +08:00
|
|
|
|
|
2021-12-12 18:19:08 +08:00
|
|
|
|
@classmethod
|
|
|
|
|
def _check_parameterless(
|
2022-09-07 09:59:05 +08:00
|
|
|
|
cls, value: Any, allow_types: Tuple[Type["Param"], ...]
|
2021-12-12 18:19:08 +08:00
|
|
|
|
) -> Optional["Param"]:
|
2022-09-07 09:59:05 +08:00
|
|
|
|
return
|
2021-11-16 18:30:16 +08:00
|
|
|
|
|
2021-12-12 18:19:08 +08:00
|
|
|
|
@abc.abstractmethod
|
|
|
|
|
async def _solve(self, **kwargs: Any) -> Any:
|
|
|
|
|
raise NotImplementedError
|
2021-11-12 20:55:59 +08:00
|
|
|
|
|
2022-09-07 09:59:05 +08:00
|
|
|
|
async def _check(self, **kwargs: Any) -> None:
|
|
|
|
|
return
|
|
|
|
|
|
2021-11-22 11:38:42 +08:00
|
|
|
|
|
2022-09-07 09:59:05 +08:00
|
|
|
|
@dataclass(frozen=True)
|
2021-12-12 18:19:08 +08:00
|
|
|
|
class Dependent(Generic[R]):
|
2022-01-21 21:04:17 +08:00
|
|
|
|
"""依赖注入容器
|
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
call: 依赖注入的可调用对象,可以是任何 Callable 对象
|
|
|
|
|
pre_checkers: 依赖注入解析前的参数检查
|
|
|
|
|
params: 具名参数列表
|
|
|
|
|
parameterless: 匿名参数列表
|
|
|
|
|
allow_types: 允许的参数类型
|
|
|
|
|
"""
|
|
|
|
|
|
2022-09-07 09:59:05 +08:00
|
|
|
|
call: _DependentCallable[R]
|
2023-06-24 14:47:35 +08:00
|
|
|
|
params: Tuple[ModelField, ...] = field(default_factory=tuple)
|
|
|
|
|
parameterless: Tuple[Param, ...] = field(default_factory=tuple)
|
2021-12-12 18:19:08 +08:00
|
|
|
|
|
2021-12-21 00:39:12 +08:00
|
|
|
|
def __repr__(self) -> str:
|
2022-09-09 11:52:57 +08:00
|
|
|
|
if inspect.isfunction(self.call) or inspect.isclass(self.call):
|
|
|
|
|
call_str = self.call.__name__
|
|
|
|
|
else:
|
|
|
|
|
call_str = repr(self.call)
|
|
|
|
|
return (
|
|
|
|
|
f"Dependent(call={call_str}"
|
|
|
|
|
+ (f", parameterless={self.parameterless}" if self.parameterless else "")
|
|
|
|
|
+ ")"
|
|
|
|
|
)
|
2021-12-21 00:39:12 +08:00
|
|
|
|
|
2021-12-12 18:19:08 +08:00
|
|
|
|
async def __call__(self, **kwargs: Any) -> R:
|
2023-09-05 00:17:55 +08:00
|
|
|
|
try:
|
|
|
|
|
# do pre-check
|
|
|
|
|
await self.check(**kwargs)
|
2022-09-07 09:59:05 +08:00
|
|
|
|
|
2023-09-05 00:17:55 +08:00
|
|
|
|
# solve param values
|
|
|
|
|
values = await self.solve(**kwargs)
|
2021-12-12 18:19:08 +08:00
|
|
|
|
|
2023-09-05 00:17:55 +08:00
|
|
|
|
# call function
|
|
|
|
|
if is_coroutine_callable(self.call):
|
|
|
|
|
return await cast(Callable[..., Awaitable[R]], self.call)(**values)
|
|
|
|
|
else:
|
|
|
|
|
return await run_sync(cast(Callable[..., R], self.call))(**values)
|
|
|
|
|
except SkippedException as e:
|
|
|
|
|
logger.trace(f"{self} skipped due to {e}")
|
|
|
|
|
raise
|
2021-11-13 19:38:01 +08:00
|
|
|
|
|
2022-09-07 09:59:05 +08:00
|
|
|
|
@staticmethod
|
|
|
|
|
def parse_params(
|
|
|
|
|
call: _DependentCallable[R], allow_types: Tuple[Type[Param], ...]
|
2023-09-03 13:39:26 +08:00
|
|
|
|
) -> Tuple[ModelField, ...]:
|
2022-09-07 09:59:05 +08:00
|
|
|
|
fields: List[ModelField] = []
|
|
|
|
|
params = get_typed_signature(call).parameters.values()
|
2021-11-13 19:38:01 +08:00
|
|
|
|
|
2022-09-07 09:59:05 +08:00
|
|
|
|
for param in params:
|
2024-01-26 11:12:57 +08:00
|
|
|
|
if isinstance(param.default, Param):
|
|
|
|
|
field_info = param.default
|
2021-12-12 18:19:08 +08:00
|
|
|
|
else:
|
2022-09-07 09:59:05 +08:00
|
|
|
|
for allow_type in allow_types:
|
|
|
|
|
if field_info := allow_type._check_param(param, allow_types):
|
|
|
|
|
break
|
|
|
|
|
else:
|
|
|
|
|
raise ValueError(
|
2023-06-24 14:47:35 +08:00
|
|
|
|
f"Unknown parameter {param.name} "
|
|
|
|
|
f"for function {call} with type {param.annotation}"
|
2022-09-07 09:59:05 +08:00
|
|
|
|
)
|
2022-08-14 19:41:00 +08:00
|
|
|
|
|
2021-12-12 18:19:08 +08:00
|
|
|
|
annotation: Any = Any
|
2024-01-26 11:12:57 +08:00
|
|
|
|
if param.annotation is not param.empty:
|
2021-12-12 18:19:08 +08:00
|
|
|
|
annotation = param.annotation
|
2022-09-07 09:59:05 +08:00
|
|
|
|
|
|
|
|
|
fields.append(
|
2024-01-26 11:12:57 +08:00
|
|
|
|
ModelField.construct(
|
|
|
|
|
name=param.name, annotation=annotation, field_info=field_info
|
2021-12-12 18:19:08 +08:00
|
|
|
|
)
|
|
|
|
|
)
|
2021-11-21 17:09:31 +08:00
|
|
|
|
|
2022-09-07 09:59:05 +08:00
|
|
|
|
return tuple(fields)
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def parse_parameterless(
|
|
|
|
|
parameterless: Tuple[Any, ...], allow_types: Tuple[Type[Param], ...]
|
|
|
|
|
) -> Tuple[Param, ...]:
|
|
|
|
|
parameterless_params: List[Param] = []
|
|
|
|
|
for value in parameterless:
|
|
|
|
|
for allow_type in allow_types:
|
|
|
|
|
if param := allow_type._check_parameterless(value, allow_types):
|
|
|
|
|
break
|
|
|
|
|
else:
|
|
|
|
|
raise ValueError(f"Unknown parameterless {value}")
|
|
|
|
|
parameterless_params.append(param)
|
|
|
|
|
return tuple(parameterless_params)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def parse(
|
|
|
|
|
cls,
|
|
|
|
|
*,
|
|
|
|
|
call: _DependentCallable[R],
|
|
|
|
|
parameterless: Optional[Iterable[Any]] = None,
|
|
|
|
|
allow_types: Iterable[Type[Param]],
|
|
|
|
|
) -> "Dependent[R]":
|
|
|
|
|
allow_types = tuple(allow_types)
|
|
|
|
|
|
|
|
|
|
params = cls.parse_params(call, allow_types)
|
|
|
|
|
parameterless_params = (
|
2023-06-24 14:47:35 +08:00
|
|
|
|
()
|
2022-09-07 09:59:05 +08:00
|
|
|
|
if parameterless is None
|
|
|
|
|
else cls.parse_parameterless(tuple(parameterless), allow_types)
|
|
|
|
|
)
|
2021-12-31 22:43:29 +08:00
|
|
|
|
|
2022-09-07 09:59:05 +08:00
|
|
|
|
return cls(call, params, parameterless_params)
|
2021-12-12 18:19:08 +08:00
|
|
|
|
|
2022-09-07 09:59:05 +08:00
|
|
|
|
async def check(self, **params: Any) -> None:
|
2023-09-05 00:17:55 +08:00
|
|
|
|
await asyncio.gather(*(param._check(**params) for param in self.parameterless))
|
|
|
|
|
await asyncio.gather(
|
|
|
|
|
*(cast(Param, param.field_info)._check(**params) for param in self.params)
|
|
|
|
|
)
|
2021-12-12 18:19:08 +08:00
|
|
|
|
|
2022-09-07 09:59:05 +08:00
|
|
|
|
async def _solve_field(self, field: ModelField, params: Dict[str, Any]) -> Any:
|
2023-08-29 18:45:12 +08:00
|
|
|
|
param = cast(Param, field.field_info)
|
|
|
|
|
value = await param._solve(**params)
|
2024-01-26 11:12:57 +08:00
|
|
|
|
if value is PydanticUndefined:
|
2022-09-07 09:59:05 +08:00
|
|
|
|
value = field.get_default()
|
2023-08-29 18:45:12 +08:00
|
|
|
|
v = check_field_type(field, value)
|
|
|
|
|
return v if param.validate else value
|
2021-12-31 22:43:29 +08:00
|
|
|
|
|
2022-09-07 09:59:05 +08:00
|
|
|
|
async def solve(self, **params: Any) -> Dict[str, Any]:
|
|
|
|
|
# solve parameterless
|
2021-12-20 00:28:02 +08:00
|
|
|
|
for param in self.parameterless:
|
|
|
|
|
await param._solve(**params)
|
|
|
|
|
|
2022-09-07 09:59:05 +08:00
|
|
|
|
# solve param values
|
|
|
|
|
values = await asyncio.gather(
|
|
|
|
|
*(self._solve_field(field, params) for field in self.params)
|
|
|
|
|
)
|
|
|
|
|
return {field.name: value for field, value in zip(self.params, values)}
|
2022-01-21 21:04:17 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
__autodoc__ = {"CustomConfig": False}
|