nonebot2/nonebot/dependencies/utils.py

57 lines
1.6 KiB
Python
Raw Normal View History

2022-01-22 15:23:07 +08:00
"""
FrontMatter:
sidebar_position: 1
description: nonebot.dependencies.utils 模块
"""
2021-11-12 20:55:59 +08:00
import inspect
from typing import Any, Dict, Callable, ForwardRef
2021-11-12 20:55:59 +08:00
2021-11-14 18:51:23 +08:00
from loguru import logger
from pydantic.fields import ModelField
2022-11-24 11:35:31 +08:00
from pydantic.typing import evaluate_forwardref
2021-11-12 20:55:59 +08:00
from nonebot.exception import TypeMisMatch
2021-11-12 20:55:59 +08:00
def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:
2022-01-21 21:04:17 +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),
)
for param in signature.parameters.values()
2021-11-12 20:55:59 +08:00
]
return inspect.Signature(typed_params)
2021-11-12 20:55:59 +08:00
def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any:
2022-01-21 21:04:17 +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(
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
def check_field_type(field: ModelField, value: Any) -> Any:
"""检查字段类型是否匹配"""
v, errs_ = field.validate(value, {}, loc=())
if errs_:
raise TypeMisMatch(field, value)
return v