image-rec / app /utils /cache.py
Zul Ikram Musaddik Rayat
implemented in-memory response caching
5129d6c
raw
history blame contribute delete
672 Bytes
from dataclasses import dataclass
import time
from asyncio import Lock
@dataclass
class Value:
data: str
birth: int
ttl_ts: int
_store = {}
_lock = Lock()
def _now() -> int:
return int(time.time())
async def create_cache(value: str, key: str, expire: int):
async with _lock:
_store[key] = Value(value, _now(), _now() + (expire or 0))
async def retrieve_cache(key: str):
async with _lock:
v = _store.get(key)
if v:
if v.ttl_ts < _now():
del _store[key]
else:
# return stored data and age
return v.data, _now() - v.birth
return None, 0