diff --git a/app/core/config.py b/app/core/config.py index c849f01e..8d6335f2 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -6,6 +6,7 @@ """ from copy import deepcopy +import asyncio from pathlib import Path from typing import Any, Dict import tomllib @@ -244,6 +245,8 @@ class Config: self._defaults = {} self._code_defaults = {} self._defaults_loaded = False + self._loaded = False + self._load_lock = asyncio.Lock() def register_defaults(self, defaults: Dict[str, Any]): """注册代码中定义的默认值""" @@ -330,9 +333,20 @@ class Config: ) self._config = merged + self._loaded = True except Exception as e: logger.error(f"Error loading config: {e}") self._config = {} + self._loaded = False + + async def ensure_loaded(self): + """确保配置至少成功加载一次(按需懒加载,线程安全)""" + if self._loaded: + return + async with self._load_lock: + if self._loaded: + return + await self.load() def get(self, key: str, default: Any = None) -> Any: """ diff --git a/main.py b/main.py index f62c12e6..9e7c70e6 100644 --- a/main.py +++ b/main.py @@ -23,12 +23,12 @@ env_file = BASE_DIR / ".env" if env_file.exists(): load_dotenv(env_file) -from fastapi import FastAPI # noqa: E402 +from fastapi import FastAPI, Request # noqa: E402 from fastapi.middleware.cors import CORSMiddleware # noqa: E402 from fastapi import Depends # noqa: E402 from app.core.auth import verify_api_key # noqa: E402 -from app.core.config import get_config # noqa: E402 +from app.core.config import config, get_config # noqa: E402 from app.core.logger import logger, setup_logging # noqa: E402 from app.core.exceptions import register_exception_handlers # noqa: E402 from app.core.response_middleware import ResponseLoggerMiddleware # noqa: E402 @@ -61,7 +61,7 @@ async def lifespan(app: FastAPI): register_defaults(get_grok_defaults()) # 2. 加载配置 - await config.load() + await config.ensure_loaded() # 3. 启动服务显示 logger.info("Starting Grok2API...") @@ -131,6 +131,11 @@ def create_app() -> FastAPI: # 请求日志和 ID 中间件 app.add_middleware(ResponseLoggerMiddleware) + @app.middleware("http") + async def ensure_config_loaded(request: Request, call_next): + await config.ensure_loaded() + return await call_next(request) + # 注册异常处理器 register_exception_handlers(app)