2022-01-22 15:23:07 +08:00
|
|
|
"""
|
|
|
|
FrontMatter:
|
|
|
|
sidebar_position: 1
|
|
|
|
description: nonebot.dependencies.utils 模块
|
|
|
|
"""
|
2023-06-24 14:47:35 +08:00
|
|
|
|
2021-11-12 20:55:59 +08:00
|
|
|
import inspect
|
2024-04-16 00:33:48 +08:00
|
|
|
from typing import Any, Callable, ForwardRef
|
2021-11-12 20:55:59 +08:00
|
|
|
|
2021-11-14 18:51:23 +08:00
|
|
|
from loguru import logger
|
2021-11-12 20:55:59 +08:00
|
|
|
|
2022-01-28 14:49:04 +08:00
|
|
|
from nonebot.exception import TypeMisMatch
|
2024-01-26 11:12:57 +08:00
|
|
|
from nonebot.typing import evaluate_forwardref
|
|
|
|
from nonebot.compat import DEFAULT_CONFIG, ModelField, model_field_validate
|
2022-01-28 14:49:04 +08:00
|
|
|
|
2021-11-12 20:55:59 +08:00
|
|
|
|
2021-12-12 18:19:08 +08:00
|
|
|
def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:
|
2022-01-21 21:04:17 +08:00
|
|
|
"""获取可调用对象签名"""
|
2023-06-24 14:47:35 +08:00
|
|
|
|
2021-12-06 10:10:51 +08:00
|
|
|
signature = inspect.signature(call)
|
|
|
|
globalns = getattr(call, "__globals__", {})
|
2021-11-12 20:55:59 +08:00
|
|
|
typed_params = [
|
|
|
|
inspect.Parameter(
|
|
|
|
name=param.name,
|
|
|
|
kind=param.kind,
|
|
|
|
default=param.default,
|
|
|
|
annotation=get_typed_annotation(param, globalns),
|
2021-11-22 23:21:26 +08:00
|
|
|
)
|
|
|
|
for param in signature.parameters.values()
|
2021-11-12 20:55:59 +08:00
|
|
|
]
|
2022-08-14 19:41:00 +08:00
|
|
|
return inspect.Signature(typed_params)
|
2021-11-12 20:55:59 +08:00
|
|
|
|
|
|
|
|
2024-04-16 00:33:48 +08:00
|
|
|
def get_typed_annotation(param: inspect.Parameter, globalns: dict[str, Any]) -> Any:
|
2022-01-21 21:04:17 +08:00
|
|
|
"""获取参数的类型注解"""
|
2023-06-24 14:47:35 +08:00
|
|
|
|
2021-11-12 20:55:59 +08:00
|
|
|
annotation = param.annotation
|
|
|
|
if isinstance(annotation, str):
|
|
|
|
annotation = ForwardRef(annotation)
|
2021-11-14 18:51:23 +08:00
|
|
|
try:
|
|
|
|
annotation = evaluate_forwardref(annotation, globalns, globalns)
|
|
|
|
except Exception as e:
|
|
|
|
logger.opt(colors=True, exception=e).warning(
|
2021-11-22 23:21:26 +08:00
|
|
|
f'Unknown ForwardRef["{param.annotation}"] for parameter {param.name}'
|
2021-11-14 18:51:23 +08:00
|
|
|
)
|
|
|
|
return inspect.Parameter.empty
|
2021-11-12 20:55:59 +08:00
|
|
|
return annotation
|
2022-01-28 14:49:04 +08:00
|
|
|
|
|
|
|
|
2023-08-29 18:45:12 +08:00
|
|
|
def check_field_type(field: ModelField, value: Any) -> Any:
|
2023-06-24 14:47:35 +08:00
|
|
|
"""检查字段类型是否匹配"""
|
|
|
|
|
2024-01-26 11:12:57 +08:00
|
|
|
try:
|
|
|
|
return model_field_validate(field, value, DEFAULT_CONFIG)
|
|
|
|
except ValueError:
|
2022-01-28 14:49:04 +08:00
|
|
|
raise TypeMisMatch(field, value)
|