初始化
This commit is contained in:
106
app/main.py
Normal file
106
app/main.py
Normal file
@@ -0,0 +1,106 @@
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from contextlib import asynccontextmanager
|
||||
import time
|
||||
|
||||
from .core.config import settings
|
||||
from .core.logging_config import setup_logging, get_logger
|
||||
from .core.database import init_db
|
||||
from .core.db_monitor import start_monitoring, get_pool_status
|
||||
from .api.work_area import router as work_area_router
|
||||
from .api.section_data import router as section_data_router
|
||||
from .api.checkpoint import router as checkpoint_router
|
||||
from .api.measurement_data import router as measurement_data_router
|
||||
|
||||
# 初始化日志系统
|
||||
setup_logging()
|
||||
logger = get_logger(__name__)
|
||||
access_logger = get_logger("uvicorn.access")
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""应用生命周期管理"""
|
||||
logger.info("应用启动中...")
|
||||
|
||||
try:
|
||||
init_db()
|
||||
logger.info("数据库初始化完成")
|
||||
except Exception as e:
|
||||
logger.error(f"数据库初始化失败: {e}")
|
||||
|
||||
try:
|
||||
start_monitoring()
|
||||
logger.info("数据库连接池监控已启动")
|
||||
pool_stats = get_pool_status()
|
||||
logger.info(f"初始连接池状态: {pool_stats}")
|
||||
except Exception as e:
|
||||
logger.error(f"数据库监控启动失败: {e}")
|
||||
|
||||
yield
|
||||
|
||||
logger.info("应用关闭中...")
|
||||
try:
|
||||
pool_stats = get_pool_status()
|
||||
logger.info(f"最终连接池状态: {pool_stats}")
|
||||
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.middleware("http")
|
||||
async def log_requests(request: Request, call_next):
|
||||
start_time = time.time()
|
||||
response = await call_next(request)
|
||||
process_time = time.time() - start_time
|
||||
access_logger.info(
|
||||
f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s"
|
||||
)
|
||||
return response
|
||||
|
||||
# 注册路由
|
||||
app.include_router(work_area_router, prefix="/api")
|
||||
app.include_router(section_data_router, prefix="/api")
|
||||
app.include_router(checkpoint_router, prefix="/api")
|
||||
app.include_router(measurement_data_router, prefix="/api")
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
"""根路径"""
|
||||
return {
|
||||
"message": "工程围岩数据信息处理系统 API",
|
||||
"version": "1.0.0",
|
||||
"docs": "/docs"
|
||||
}
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
"""健康检查"""
|
||||
return {"status": "healthy", "database": "connected"}
|
||||
|
||||
@app.get("/api/monitor/pool")
|
||||
async def get_pool_monitor():
|
||||
"""获取连接池状态"""
|
||||
return get_pool_status()
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def global_exception_handler(request: Request, exc: Exception):
|
||||
"""全局异常处理"""
|
||||
import traceback
|
||||
logger.error(f"全局异常: {type(exc).__name__}: {exc}\n{traceback.format_exc()}")
|
||||
return {"detail": f"服务器内部错误: {type(exc).__name__}", "status_code": 500}
|
||||
Reference in New Issue
Block a user