nonebot2/nonebot/dependencies/models.py

60 lines
1.6 KiB
Python
Raw Normal View History

import abc
import inspect
from typing import Any, List, Type, Callable, Optional
2021-11-12 20:55:59 +08:00
from pydantic.fields import FieldInfo, ModelField
2021-11-12 20:55:59 +08:00
2021-11-15 21:44:24 +08:00
from nonebot.utils import get_name
2021-11-13 19:38:01 +08:00
2021-11-12 20:55:59 +08:00
class Param(FieldInfo, abc.ABC):
def __repr__(self) -> str:
return f"{self.__class__.__name__}"
def __str__(self) -> str:
return repr(self)
@classmethod
@abc.abstractmethod
def _check(cls, name: str, param: inspect.Parameter) -> bool:
raise NotImplementedError
@abc.abstractmethod
def _solve(self, **kwargs: Any) -> Any:
raise NotImplementedError
class DependsWrapper:
2021-11-12 20:55:59 +08:00
def __init__(self,
dependency: Optional[Callable[..., Any]] = None,
*,
use_cache: bool = True) -> None:
self.dependency = dependency
self.use_cache = use_cache
def __repr__(self) -> str:
dep = get_name(self.dependency)
cache = "" if self.use_cache else ", use_cache=False"
return f"{self.__class__.__name__}({dep}{cache})"
class Dependent:
def __init__(self,
*,
func: Optional[Callable[..., Any]] = None,
name: Optional[str] = None,
2021-11-15 21:44:24 +08:00
params: Optional[List[ModelField]] = None,
allow_types: Optional[List[Type[Param]]] = None,
2021-11-12 20:55:59 +08:00
dependencies: Optional[List["Dependent"]] = None,
use_cache: bool = True) -> None:
self.func = func
self.name = name
2021-11-15 21:44:24 +08:00
self.params = params or []
self.allow_types = allow_types or []
2021-11-12 20:55:59 +08:00
self.dependencies = dependencies or []
self.use_cache = use_cache
self.cache_key = self.func