From a539a7d096312d01340acb2f309c99ded13bb883 Mon Sep 17 00:00:00 2001 From: aszerW Date: Thu, 7 May 2026 23:57:19 +0800 Subject: [PATCH] =?UTF-8?q?fix(api):=20=E4=BF=AE=E5=A4=8D=E7=BC=93?= =?UTF-8?q?=E5=AD=98=E7=8A=B6=E6=80=81=E5=88=A4=E6=96=AD=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - fetch_data_with_ttl 返回 (data, is_cached) 元组 - 修复 cached 字段始终为 false 的问题 - 批量接口适配新的返回格式 --- core/datasource/flask_server.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/core/datasource/flask_server.py b/core/datasource/flask_server.py index e1e8fba..9391b01 100644 --- a/core/datasource/flask_server.py +++ b/core/datasource/flask_server.py @@ -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