diff --git a/datasource/flask_server.py b/datasource/flask_server.py index 4ba63a5..f94e6c0 100644 --- a/datasource/flask_server.py +++ b/datasource/flask_server.py @@ -119,20 +119,30 @@ def get_fetcher() -> UniversalDataFetcher: @lru_cache(maxsize=CACHE_MAXSIZE) def _fetch_full_data_cached(code: str, today: str) -> Optional[str]: """ - 缓存全量数据(从 DEFAULT_START_DATE 到 today) + 缓存全量数据(仅日级别数据) + + 缓存策略: + - 日级别数据(股票/指数/ETF/期货): 从 DEFAULT_START_DATE 到 today + - 加密货币: 不缓存,每次实时下载 缓存Key: (code, today_date) - today: 实际的今天日期,用于每日更新缓存 - - 每天下载一次全量数据,避免重复请求 Returns: - JSON 序列化的全量数据 + JSON 序列化的全量数据(仅日级别数据) """ f = get_fetcher() + # 检查资产类型 + asset_type = AssetTypeDetector.detect(code) + + # 加密货币不缓存 + if asset_type == AssetType.CRYPTO: + return None # 不缓存加密货币 + try: with f: - # 下载全量数据:从默认起点到今天 + # 下载数据:从默认起点到今天 df = f.fetch(code, DEFAULT_START_DATE, today) if df is None or len(df) == 0: @@ -142,9 +152,10 @@ def _fetch_full_data_cached(code: str, today: str) -> Optional[str]: result = { 'df_json': dataframe_to_json(df), 'code': code, - 'asset_type': AssetTypeDetector.detect(code).value, + 'asset_type': asset_type.value, 'data_start': df.index.min().strftime('%Y-%m-%d') if len(df) > 0 else None, 'data_end': df.index.max().strftime('%Y-%m-%d') if len(df) > 0 else None, + 'cache_strategy': 'full_history', } return json.dumps(result) @@ -215,12 +226,11 @@ def fetch_data_with_ttl( nocache: bool = False ) -> Tuple[Optional[Dict], bool]: """ - 获取数据,支持 TTL 缓存 + 获取数据,支持 TTL 缓存(加密货币不缓存) 缓存策略: - - Key: (code, today_date) 缓存全量数据 - - 每天下载一次全量数据(从 DEFAULT_START_DATE 到今天) - - 用户请求时从缓存切片 start-end 范围返回 + - 日级别数据(股票/指数/ETF/期货): Key=(code, today), 缓存全量数据,切片返回 + - 加密货币: 每次实时下载,不缓存 Args: code: 标的代码 @@ -229,10 +239,32 @@ def fetch_data_with_ttl( nocache: 是否跳过缓存 Returns: - (data, is_cached): 切片后的数据和是否命中缓存 + (data, is_cached): 数据和是否命中缓存 """ # 获取今天的实际日期(用于缓存Key) today = datetime.now().strftime('%Y-%m-%d') + + # 检查资产类型 + asset_type = AssetTypeDetector.detect(code) + + # 加密货币:直接下载,不缓存 + if asset_type == AssetType.CRYPTO: + f = get_fetcher() + try: + with f: + df = f.fetch(code, start, end) + if df is None or len(df) == 0: + return None, False + result = dataframe_to_json(df) + result['code'] = code + result['asset_type'] = asset_type.value + result['cache_strategy'] = 'no_cache_crypto' + result['requested_range'] = {'start': start, 'end': end} + return result, False + except Exception as e: + return {'error': str(e), 'code': code, 'asset_type': asset_type.value}, False + + # 日级别数据:使用缓存 full_cache_key = (code, today) # 跳过缓存:清理缓存后重新下载