111 lines
3.0 KiB
Python
111 lines
3.0 KiB
Python
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from contextlib import asynccontextmanager
|
|
from sqlalchemy import text
|
|
|
|
from app.config import settings
|
|
from app.database import engine
|
|
from app.routes import router
|
|
from app.logger import get_logger, LoggerManager
|
|
|
|
|
|
# 初始化日志系统
|
|
LoggerManager.setup_logging()
|
|
logger = get_logger("main")
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
# 启动时初始化
|
|
logger.info("🚀 应用启动中...")
|
|
|
|
try:
|
|
# 验证数据库连接
|
|
logger.info("📊 验证数据库连接...")
|
|
try:
|
|
async with engine.begin() as conn:
|
|
# 执行简单的查询来验证连接
|
|
result = await conn.execute(text("SELECT 1"))
|
|
connection_test = result.scalar()
|
|
if connection_test == 1:
|
|
logger.info("✅ 数据库连接验证成功")
|
|
else:
|
|
raise Exception("数据库连接测试失败")
|
|
except Exception as db_error:
|
|
logger.error(f"❌ 数据库连接验证失败: {db_error}")
|
|
raise
|
|
|
|
logger.info(f"🎉 {settings.app_name} 启动完成!")
|
|
yield
|
|
|
|
except Exception as e:
|
|
logger.error(f"❌ 应用启动失败: {e}")
|
|
raise
|
|
|
|
finally:
|
|
# 关闭时清理
|
|
logger.info("🛑 应用关闭中...")
|
|
logger.info("👋 应用已关闭")
|
|
|
|
|
|
app = FastAPI(
|
|
title=settings.app_name,
|
|
version="1.0.0",
|
|
lifespan=lifespan,
|
|
docs_url=(
|
|
"/docs"
|
|
if not settings.disable_docs and settings.environment != "production"
|
|
else None
|
|
),
|
|
redoc_url=(
|
|
"/redoc"
|
|
if not settings.disable_docs and settings.environment != "production"
|
|
else None
|
|
),
|
|
openapi_url="/openapi.json" if not settings.disable_docs else None,
|
|
)
|
|
|
|
# 添加CORS中间件
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
# 注册路由
|
|
app.include_router(router)
|
|
|
|
|
|
@app.get("/")
|
|
async def root():
|
|
# 检查环境,生产环境下禁用根接口
|
|
if settings.environment == "production":
|
|
logger.warning("🚫 生产环境下禁止访问根接口")
|
|
from fastapi import HTTPException
|
|
|
|
raise HTTPException(status_code=404, detail="Not Found")
|
|
|
|
logger.info("📝 根接口被访问")
|
|
return {"message": f"Welcome to {settings.app_name}"}
|
|
|
|
|
|
@app.get("/health")
|
|
async def health_check():
|
|
# 检查环境,生产环境下禁用健康检查接口
|
|
if settings.environment == "production":
|
|
logger.warning("🚫 生产环境下禁止访问健康检查接口")
|
|
from fastapi import HTTPException
|
|
|
|
raise HTTPException(status_code=404, detail="Not Found")
|
|
|
|
logger.debug("💓 健康检查接口被访问")
|
|
return {"status": "healthy"}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
|
|
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=settings.debug)
|