Files
TJWaterServerBinary/app/main.py
T
jiang fa188af0b1 refactor(db)!: adopt project-routed pooled databases
Reorganize WNDB by responsibility and remove legacy scheme endpoints.\n\nRoute analysis and time-series access through project pools, preserve transactional realtime replacement, and refresh GIS materialized views after writes.\n\nAdd database architecture documentation, live pooling coverage, API contract updates, and executable container verification.\n\nBREAKING CHANGE: legacy scheme APIs and flat app.native.wndb module imports are removed.
2026-08-25 18:35:05 +08:00

80 lines
2.5 KiB
Python

from fastapi import FastAPI
from contextlib import asynccontextmanager
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.middleware.cors import CORSMiddleware
import logging
from datetime import datetime
import app.services.project_info as project_info
from app.api.problem_details import install_problem_details_handlers
from app.api.v1.rest_router import api_router
from app.infra.db.dynamic_manager import project_connection_manager
from app.infra.db.metadb.database import close_metadata_engine
from app.infra.db.timescaledb.sync_pool import close_all_timescale_pools
from app.native.wndb.core.connection import close_all_project_pools
from app.services.tjnetwork import open_project
from app.core.config import settings
# 导入审计中间件
from app.infra.audit.middleware import AuditMiddleware
logger = logging.getLogger()
logger.setLevel(logging.INFO)
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("**********************************************************")
logger.info(str(datetime.now()))
logger.info("TJWater CloudService is starting...")
logger.info("**********************************************************")
if project_info.name:
print(project_info.name)
open_project(project_info.name)
yield
# 清理资源
await project_connection_manager.close_all()
close_all_timescale_pools()
close_all_project_pools()
await close_metadata_engine()
logger.info("Database connections closed")
# 根据环境配置决定是否启用文档
is_production = settings.ENVIRONMENT.lower() == "production"
app = FastAPI(
lifespan=lifespan,
title=settings.PROJECT_NAME,
description="TJWater Server - 供水管网智能管理系统",
version="1.0.0",
docs_url=None if is_production else "/docs",
redoc_url=None if is_production else "/redoc",
openapi_url=None if is_production else "/openapi.json",
redirect_slashes=False,
)
# Include Routers
app.include_router(api_router, prefix="/api/v1")
install_problem_details_handlers(app)
# Legcy Routers without version prefix
# app.include_router(api_router)
# 配置中间件
app.add_middleware(GZipMiddleware, minimum_size=1000)
# 添加审计中间件(可选,记录关键操作)
app.add_middleware(AuditMiddleware)
# 配置 CORS 中间件
# 确保这是你最后一个添加的 app.add_middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 允许所有来源
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)