100 lines
2.7 KiB
Python
100 lines
2.7 KiB
Python
from fastapi import FastAPI, HTTPException
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from contextlib import asynccontextmanager
|
|
import logging
|
|
|
|
from .core.config import settings
|
|
from .core.logging_config import setup_logging, get_logger
|
|
from .core.database import init_db
|
|
from .api.account import router as account_router
|
|
from .api.database import router as database_router
|
|
from .api.task import router as task_router
|
|
from .api.comprehensive_data import router as comprehensive_data_router
|
|
from .utils.scheduler import task_scheduler
|
|
|
|
# 初始化日志系统
|
|
setup_logging()
|
|
logger = get_logger(__name__)
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
"""应用生命周期管理"""
|
|
# 启动时执行
|
|
logger.info("应用启动中...")
|
|
|
|
# 初始化数据库
|
|
try:
|
|
init_db()
|
|
logger.info("数据库初始化完成")
|
|
except Exception as e:
|
|
logger.error(f"数据库初始化失败: {e}")
|
|
|
|
# 启动定时任务调度器
|
|
try:
|
|
task_scheduler.start()
|
|
logger.info("定时任务调度器启动完成")
|
|
except Exception as e:
|
|
logger.error(f"定时任务调度器启动失败: {e}")
|
|
|
|
yield
|
|
|
|
# 关闭时执行
|
|
logger.info("应用关闭中...")
|
|
try:
|
|
task_scheduler.shutdown()
|
|
logger.info("定时任务调度器已关闭")
|
|
except Exception as e:
|
|
logger.error(f"定时任务调度器关闭失败: {e}")
|
|
|
|
# 创建FastAPI应用
|
|
app = FastAPI(
|
|
title="铁路项目管理系统",
|
|
description="基于FastAPI、MySQL、SQLAlchemy的铁路项目管理系统",
|
|
version="1.0.0",
|
|
lifespan=lifespan
|
|
)
|
|
|
|
# 配置CORS
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"], # 生产环境建议配置具体域名
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
# 注册路由
|
|
app.include_router(account_router, prefix="/api")
|
|
app.include_router(database_router, prefix="/api")
|
|
app.include_router(task_router, prefix="/api")
|
|
app.include_router(comprehensive_data_router, prefix="/api")
|
|
|
|
# 根路径
|
|
@app.get("/")
|
|
async def root():
|
|
"""根路径"""
|
|
return {
|
|
"message": "铁路项目管理系统 API",
|
|
"version": "1.0.0",
|
|
"docs": "/docs",
|
|
"redoc": "/redoc"
|
|
}
|
|
|
|
# 健康检查
|
|
@app.get("/health")
|
|
async def health_check():
|
|
"""健康检查"""
|
|
return {
|
|
"status": "healthy",
|
|
"database": "connected",
|
|
"scheduler": "running" if task_scheduler.scheduler.running else "stopped"
|
|
}
|
|
|
|
# 全局异常处理
|
|
@app.exception_handler(Exception)
|
|
async def global_exception_handler(request, exc):
|
|
logger.error(f"全局异常: {str(exc)}")
|
|
return HTTPException(
|
|
status_code=500,
|
|
detail="服务器内部错误"
|
|
) |