mirror of
https://github.com/snailyp/gemini-balance.git
synced 2026-05-19 02:29:31 +08:00
重构项目目录结构,提高代码组织性和可维护性 将schemas目录重命名为domain,更好地表达领域模型概念 将services目录细分为service/chat、service/image等子目录 将api目录重命名为router,更符合FastAPI惯例 创建utils目录存放通用工具函数 更新FastAPI应用程序生命周期管理 替换已弃用的on_event方法为推荐的lifespan事件处理器 添加应用程序关闭时的日志记录 代码质量改进 抽取常量到constants.py,减少硬编码值 添加helpers.py提供通用工具函数 优化配置管理,使用环境变量和默认值 完善文档字符串,提高代码可读性
72 lines
1.9 KiB
Python
72 lines
1.9 KiB
Python
"""
|
||
应用程序工厂模块,负责创建和配置FastAPI应用程序实例
|
||
"""
|
||
from contextlib import asynccontextmanager
|
||
from fastapi import FastAPI
|
||
from fastapi.staticfiles import StaticFiles
|
||
|
||
from app.config.config import settings
|
||
from app.logger.logger import get_main_logger
|
||
from app.middleware.middleware import setup_middlewares
|
||
from app.exception.exceptions import setup_exception_handlers
|
||
from app.router.routers import setup_routers
|
||
from app.service.key.key_manager import get_key_manager_instance
|
||
from app.core.initialization import initialize_app
|
||
|
||
logger = get_main_logger()
|
||
|
||
@asynccontextmanager
|
||
async def lifespan(app: FastAPI):
|
||
"""
|
||
应用程序生命周期管理器
|
||
|
||
Args:
|
||
app: FastAPI应用实例
|
||
"""
|
||
# 启动事件
|
||
logger.info("Application starting up...")
|
||
try:
|
||
# 初始化KeyManager
|
||
await get_key_manager_instance(settings.API_KEYS)
|
||
logger.info("KeyManager initialized successfully")
|
||
except Exception as e:
|
||
logger.error(f"Failed to initialize KeyManager: {str(e)}")
|
||
raise
|
||
|
||
yield # 应用程序运行期间
|
||
|
||
# 关闭事件
|
||
logger.info("Application shutting down...")
|
||
|
||
def create_app() -> FastAPI:
|
||
"""
|
||
创建并配置FastAPI应用程序实例
|
||
|
||
Returns:
|
||
FastAPI: 配置好的FastAPI应用程序实例
|
||
"""
|
||
# 初始化应用程序
|
||
initialize_app()
|
||
|
||
# 创建FastAPI应用
|
||
app = FastAPI(
|
||
title="Gemini Balance API",
|
||
description="Gemini API代理服务,支持负载均衡和密钥管理",
|
||
version="1.0.0",
|
||
lifespan=lifespan
|
||
)
|
||
|
||
# 配置静态文件
|
||
app.mount("/static", StaticFiles(directory="app/static"), name="static")
|
||
|
||
# 配置中间件
|
||
setup_middlewares(app)
|
||
|
||
# 配置异常处理器
|
||
setup_exception_handlers(app)
|
||
|
||
# 配置路由
|
||
setup_routers(app)
|
||
|
||
return app
|