Spaces:
Running
Running
File size: 1,521 Bytes
553a29d 8b70b45 553a29d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | # 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 小时
|