Merge pull request #314 from FaiChou/fix/vercel-serverless-db-init

fix: ensure SQL storage initializes in Vercel serverless runtime
This commit is contained in:
Chenyme authored and GitHub committed 2026-03-17 15:35:35 +08:00
commit 9c48d58ffc
2 files changed
+22 -3

No files matched your search

+14
View File
@@ -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:
"""
+8 -3
View File
@@ -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)