1
from functools import wraps
4
from .base import BaseBackend, BaseKeyMaker
5
from .cache_tag import CacheTag
13
def init(self, *, backend: BaseBackend, key_maker: BaseKeyMaker) -> None:
14
self.backend = backend
15
self.key_maker = key_maker
20
prefix: str | None = None,
21
tag: CacheTag | None = None,
24
def _cached(function):
26
async def __cached(*args, **kwargs):
27
if not self.backend or not self.key_maker:
28
raise Exception("backend or key_maker is None")
30
key = await self.key_maker.make(
32
prefix=prefix if prefix else tag.value,
34
cached_response = await self.backend.get(key=key)
36
return cached_response
38
response = await function(*args, **kwargs)
39
await self.backend.set(response=response, key=key, ttl=ttl)
46
async def set(self, *, tag: CacheTag, key: str, response=Any, ttl=None) -> None:
47
key = f'{tag.value}:{key}'
49
await self.backend.set(response=response, key=key, ttl=ttl)
51
pass #TODO: Надо убрать потом
54
async def set_model(self, module, model, key: str, data=Any, ttl=10000) -> None:
55
key = f'{CacheTag.MODEL.value}:{module}:{model}:{key}'
56
await self.backend.set(response=data, key=key, ttl=ttl)
59
async def get_model(self, module, model, key: str) -> None:
60
key = f'{CacheTag.MODEL.value}:{module}:{model}:{key}'
61
return await self.backend.get(key=key)
63
def clean_model_tag(self, data, module, model):
65
async def get_by_model_all(self, module, model) -> dict:
66
key = f'{CacheTag.MODEL.value}:{module}:{model}'
67
data = await self.backend.get_startswith(key=key)
69
for key, value in data.items():
71
key.split(':')[-1]: value
75
async def get_by_tag(self, tag) -> dict:
76
data = await self.backend.get_startswith(key=tag)
78
for key, value in data.items():
80
key.split(':')[-1]: value
84
async def get(self, tag: CacheTag, key):
85
key = f'{tag.value}:{key}'
86
return await self.backend.get(key=key)
89
async def remove_by_tag(self, *, tag: CacheTag, key:str=None) -> None:
90
key = f'{tag.value}:{key}'
91
await self.backend.delete_startswith(key=key)
93
async def remove_by_prefix(self, *, prefix: str) -> None:
94
await self.backend.delete_startswith(value=prefix)