cache.py 520 B

12345678910111213141516171819202122232425
  1. from __future__ import annotations
  2. from time import time
  3. from typing import Any
  4. _CACHE: dict[str, tuple[float, Any]] = {}
  5. def get_cache(key: str):
  6. item = _CACHE.get(key)
  7. if not item:
  8. return None
  9. expires_at, value = item
  10. if time() >= expires_at:
  11. _CACHE.pop(key, None)
  12. return None
  13. return value
  14. def set_cache(key: str, value: Any, ttl_seconds: int):
  15. _CACHE[key] = (time() + ttl_seconds, value)
  16. def cache_stats() -> dict[str, int]:
  17. return {"entries": len(_CACHE)}