Files
fastapi-cache/fastapi_cache/__init__.py

66 lines
1.8 KiB
Python
Raw Normal View History

2022-10-22 20:59:37 +04:00
from typing import Callable, Optional, Type
2022-10-22 20:59:37 +04:00
from fastapi_cache.backends import Backend
from fastapi_cache.coder import Coder, JsonCoder
from fastapi_cache.key_builder import default_key_builder
2020-08-26 18:04:57 +08:00
class FastAPICache:
2022-10-22 20:59:37 +04:00
_backend: Optional[Backend] = None
_prefix: Optional[str] = None
_expire: Optional[int] = None
2020-10-08 15:10:34 +08:00
_init = False
2022-10-22 20:59:37 +04:00
_coder: Optional[Type[Coder]] = None
_key_builder: Optional[Callable] = None
2021-10-28 15:52:21 +08:00
_enable = True
2020-08-26 18:04:57 +08:00
@classmethod
def init(
cls,
2022-10-22 20:59:37 +04:00
backend: Backend,
prefix: str = "",
2022-10-22 20:59:37 +04:00
expire: Optional[int] = None,
coder: Type[Coder] = JsonCoder,
key_builder: Callable = default_key_builder,
2021-10-28 15:52:21 +08:00
enable: bool = True,
2022-10-22 20:59:37 +04:00
) -> None:
2020-10-08 15:10:34 +08:00
if cls._init:
return
cls._init = True
2020-08-26 18:04:57 +08:00
cls._backend = backend
cls._prefix = prefix
2020-10-08 15:10:34 +08:00
cls._expire = expire
cls._coder = coder
cls._key_builder = key_builder
2021-10-28 15:52:21 +08:00
cls._enable = enable
2020-08-26 18:04:57 +08:00
@classmethod
2022-10-22 20:59:37 +04:00
def get_backend(cls) -> Backend:
2020-08-26 18:04:57 +08:00
assert cls._backend, "You must call init first!" # nosec: B101
return cls._backend
@classmethod
2022-10-22 20:59:37 +04:00
def get_prefix(cls) -> Optional[str]:
2020-08-26 18:04:57 +08:00
return cls._prefix
2020-10-08 15:10:34 +08:00
@classmethod
2022-10-22 20:59:37 +04:00
def get_expire(cls) -> Optional[int]:
2020-10-08 15:10:34 +08:00
return cls._expire
@classmethod
2022-10-22 20:59:37 +04:00
def get_coder(cls) -> Optional[Type[Coder]]:
return cls._coder
@classmethod
2022-10-22 20:59:37 +04:00
def get_key_builder(cls) -> Optional[Callable]:
return cls._key_builder
2020-11-03 18:08:06 +08:00
2021-10-28 15:52:21 +08:00
@classmethod
2022-10-22 20:59:37 +04:00
def get_enable(cls) -> bool:
2021-10-28 15:52:21 +08:00
return cls._enable
2020-11-03 18:08:06 +08:00
@classmethod
2022-10-22 20:59:37 +04:00
async def clear(cls, namespace: Optional[str] = None, key: Optional[str] = None) -> int:
namespace = cls._prefix + (":" + namespace if namespace else "")
2020-11-03 18:08:06 +08:00
return await cls._backend.clear(namespace, key)