ResearchRadar / cache.py
ZZZyx3587's picture
Upload cache.py with huggingface_hub
8b70b45 verified
# cache.py
# ============================================================
# 类型:公共工具(乙负责)
# 功能:内存缓存,避免并发用户重复请求相同 API 数据,
# 降低 GitHub/arxiv/S2 限速风险
# ============================================================
import time
import threading
class TTLCache:
"""简单的 TTL 内存缓存,线程安全"""
def __init__(self, ttl_seconds: int = 1800):
self._store: dict[str, tuple[float, object]] = {}
self._ttl = ttl_seconds
self._lock = threading.Lock()
def get(self, key: str) -> object | None:
with self._lock:
entry = self._store.get(key)
if entry is None:
return None
ts, value = entry
if time.time() - ts > self._ttl:
del self._store[key]
return None
return value
def set(self, key: str, value: object):
with self._lock:
self._store[key] = (time.time(), value)
def clear(self):
with self._lock:
self._store.clear()
# 全局缓存实例
arxiv_cache = TTLCache(ttl_seconds=1800) # 论文元信息: 30 分钟
s2_cache = TTLCache(ttl_seconds=1800) # S2 搜索结果: 30 分钟
github_search_cache = TTLCache(ttl_seconds=900) # GitHub 搜索结果: 15 分钟
github_readme_cache = TTLCache(ttl_seconds=3600) # GitHub README: 1 小时
github_deps_cache = TTLCache(ttl_seconds=3600) # GitHub 依赖: 1 小时