from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware import os import logging from dotenv import load_dotenv from app.routers import qcloud_router, dress_router, tryon_router from app.utils.config import get_settings from app.utils.response import APIResponse from app.database import Base, engine from app.middleware import ResponseWrapperMiddleware from app.exceptions import setup_exception_handlers # 创建数据库表 Base.metadata.create_all(bind=engine) # 加载环境变量 load_dotenv(dotenv_path=".env") # 配置日志 logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) app = FastAPI( title="AI-Dressing API", description="基于 DashScope 的 AI 服务 API", version="0.1.0", ) # 添加 CORS 中间件 app.add_middleware( CORSMiddleware, allow_origins=["*"], # 在生产环境中,应该指定确切的域名 allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 添加响应包装中间件 app.add_middleware(ResponseWrapperMiddleware) # 设置异常处理 setup_exception_handlers(app) # 注册路由 app.include_router(qcloud_router.router, prefix="/api/qcloud", tags=["腾讯云"]) app.include_router(dress_router.router, prefix="/api/dresses", tags=["服装"]) app.include_router(tryon_router.router, prefix="/api/tryons", tags=["试穿"]) @app.get("/", tags=["健康检查"]) async def root(): """API 根端点""" return APIResponse.ok(message="服务运行中") @app.get("/health", tags=["健康检查"]) async def health_check(): """健康检查端点,用于Docker容器健康监控""" health_data = {"checks": {}} health_status = "healthy" health_message = "服务运行正常" # 检查数据库连接 try: from app.database import SessionLocal db = SessionLocal() db.execute("SELECT 1") db.close() health_data["checks"]["database"] = {"status": "healthy", "message": "数据库连接正常"} except Exception as e: health_status = "unhealthy" health_message = "服务异常" health_data["checks"]["database"] = {"status": "unhealthy", "message": f"数据库连接失败: {str(e)}"} # 检查API密钥 if os.getenv("DASHSCOPE_API_KEY"): health_data["checks"]["dashscope"] = {"status": "configured", "message": "DashScope API密钥已配置"} else: health_data["checks"]["dashscope"] = {"status": "missing", "message": "DashScope API密钥未配置"} if os.getenv("QCLOUD_SECRET_ID") and os.getenv("QCLOUD_SECRET_KEY"): health_data["checks"]["qcloud"] = {"status": "configured", "message": "腾讯云凭证已配置"} else: health_data["checks"]["qcloud"] = {"status": "missing", "message": "腾讯云凭证未配置"} if health_status == "healthy": return APIResponse.ok(data=health_data, message=health_message) else: return APIResponse.error(message=health_message, code=503, data=health_data) @app.get("/info", tags=["服务信息"]) async def get_info(): """获取服务基本信息""" settings = get_settings() info_data = { "app_name": "AI-Dressing API", "version": "0.1.0", "debug_mode": settings.debug, } return APIResponse.ok(data=info_data, message="服务信息获取成功") if __name__ == "__main__": import uvicorn settings = get_settings() uvicorn.run( "app.main:app", host=settings.host, port=settings.port, reload=settings.debug, )