123 lines
3.5 KiB
Python
123 lines
3.5 KiB
Python
from fastapi import FastAPI, HTTPException
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from fastapi.responses import JSONResponse
|
||
import uvicorn
|
||
import logging
|
||
from contextlib import asynccontextmanager
|
||
|
||
# 导入路由模块
|
||
from api.v1.routes.database import router as database_router
|
||
from api.v1.routes.tables import router as tables_router
|
||
from database_manager import db_manager
|
||
from sample_data import SampleDataInitializer
|
||
|
||
# 配置日志
|
||
logging.basicConfig(
|
||
level=logging.INFO,
|
||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||
)
|
||
logger = logging.getLogger(__name__)
|
||
|
||
# 应用生命周期管理
|
||
@asynccontextmanager
|
||
async def lifespan(app: FastAPI):
|
||
"""应用启动和关闭时的处理"""
|
||
# 启动时
|
||
logger.info("数据库接口服务启动中...")
|
||
|
||
# 初始化示例数据
|
||
try:
|
||
logger.info("开始初始化示例数据...")
|
||
sample_initializer = SampleDataInitializer()
|
||
sample_initializer.initialize_all_sample_data()
|
||
logger.info("示例数据初始化完成")
|
||
except Exception as e:
|
||
logger.warning(f"示例数据初始化失败: {str(e)}")
|
||
logger.info("服务将继续启动,但示例数据不可用")
|
||
|
||
yield
|
||
# 关闭时
|
||
logger.info("数据库接口服务关闭中...")
|
||
# 关闭所有数据库连接
|
||
for connection_id in db_manager.list_connections():
|
||
db_manager.close_connection(connection_id)
|
||
logger.info("所有数据库连接已关闭")
|
||
|
||
# 创建FastAPI应用
|
||
app = FastAPI(
|
||
title="数据库接口服务",
|
||
description="提供统一的数据库管理接口,支持MySQL、Oracle、SQL Server、PostgreSQL等多种数据库类型",
|
||
version="1.0.0",
|
||
docs_url="/docs",
|
||
redoc_url="/redoc",
|
||
lifespan=lifespan
|
||
)
|
||
|
||
# 添加CORS中间件
|
||
app.add_middleware(
|
||
CORSMiddleware,
|
||
allow_origins=["*"], # 在生产环境中应该设置具体的域名
|
||
allow_credentials=True,
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
)
|
||
|
||
# 全局异常处理
|
||
@app.exception_handler(Exception)
|
||
async def global_exception_handler(request, exc):
|
||
"""全局异常处理器"""
|
||
logger.error(f"全局异常: {str(exc)}")
|
||
return JSONResponse(
|
||
status_code=500,
|
||
content={
|
||
"success": False,
|
||
"message": "服务器内部错误",
|
||
"error": str(exc)
|
||
}
|
||
)
|
||
|
||
|
||
# 健康检查接口
|
||
@app.get("/health", tags=["系统"])
|
||
async def health_check():
|
||
"""健康检查接口"""
|
||
return {
|
||
"success": True,
|
||
"message": "服务运行正常",
|
||
"data": {
|
||
"status": "healthy",
|
||
"active_connections": len(db_manager.list_connections())
|
||
}
|
||
}
|
||
|
||
|
||
# 根路径接口
|
||
@app.get("/", tags=["系统"])
|
||
async def root():
|
||
"""根路径接口"""
|
||
return {
|
||
"success": True,
|
||
"message": "欢迎使用数据库接口服务",
|
||
"data": {
|
||
"title": "数据库接口服务",
|
||
"version": "1.0.0",
|
||
"description": "提供统一的数据库管理接口,支持MySQL、Oracle、SQL Server、PostgreSQL等多种数据库类型",
|
||
"docs_url": "/docs",
|
||
"redoc_url": "/redoc"
|
||
}
|
||
}
|
||
|
||
# 注册路由
|
||
app.include_router(database_router, prefix="/api/v1", tags=["数据库管理"])
|
||
app.include_router(tables_router, prefix="/api/v1", tags=["表管理"])
|
||
|
||
# 主函数
|
||
if __name__ == "__main__":
|
||
logger.info("启动数据库接口服务...")
|
||
uvicorn.run(
|
||
"main:app",
|
||
host="0.0.0.0",
|
||
port=8000,
|
||
log_level="info"
|
||
)
|