fix(api): 修复缓存状态判断逻辑

- fetch_data_with_ttl 返回 (data, is_cached) 元组
- 修复 cached 字段始终为 false 的问题
- 批量接口适配新的返回格式
This commit is contained in:
2026-05-07 23:57:19 +08:00
parent 7cf20268cf
commit a539a7d096

View File

@@ -137,14 +137,17 @@ def _fetch_data_cached(code: str, start: str, end: str, retry: int) -> Optional[
return json.dumps({"error": str(e)})
def fetch_data_with_ttl(code: str, start: str, end: str, retry: int = 3, nocache: bool = False) -> Optional[Dict]:
def fetch_data_with_ttl(code: str, start: str, end: str, retry: int = 3, nocache: bool = False) -> tuple[Optional[Dict], bool]:
"""
获取数据支持TTL缓存
Returns:
(data, is_cached): 数据和是否命中缓存
"""
if nocache:
# 直接获取,不使用缓存
result_json = _fetch_data_cached.__wrapped__(code, start, end, retry)
return json.loads(result_json) if result_json else None
return (json.loads(result_json) if result_json else None, False)
# 使用缓存
cache_key = (code, start, end, retry)
@@ -154,7 +157,7 @@ def fetch_data_with_ttl(code: str, start: str, end: str, retry: int = 3, nocache
if cache_key in fetch_data_with_ttl._ttl_cache:
entry = fetch_data_with_ttl._ttl_cache[cache_key]
if not entry.is_expired():
return entry.data
return entry.data, True
# 过期,删除
del fetch_data_with_ttl._ttl_cache[cache_key]
else:
@@ -164,14 +167,14 @@ def fetch_data_with_ttl(code: str, start: str, end: str, retry: int = 3, nocache
result_json = _fetch_data_cached(code, start, end, retry)
if result_json is None:
return None
return None, False
result = json.loads(result_json)
# 存入TTL缓存
fetch_data_with_ttl._ttl_cache[cache_key] = TimedCacheEntry(result)
return result
return result, False
def clear_data_cache():
@@ -422,7 +425,7 @@ def get_ohlcv():
retry_count = 3
# 使用缓存获取数据
result = fetch_data_with_ttl(code, start, end, retry_count, nocache)
result, is_cached = fetch_data_with_ttl(code, start, end, retry_count, nocache)
if result is None:
return jsonify({
@@ -443,7 +446,7 @@ def get_ohlcv():
}), 500
# 添加缓存状态
result['cached'] = not nocache and _fetch_data_cached.cache_info().hits > 0
result['cached'] = is_cached
return jsonify(result)
@@ -520,7 +523,7 @@ def batch_ohlcv():
for code in codes:
try:
# 使用缓存获取数据
result = fetch_data_with_ttl(code, start, end, retry, nocache=False)
result, _ = fetch_data_with_ttl(code, start, end, retry, nocache=False)
if result is not None and "error" not in result:
results[code] = result