Spaces:
Sleeping
Sleeping
from dataclasses import dataclass | |
import time | |
from asyncio import Lock | |
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 | |