109 lines
3.5 KiB
Python
109 lines
3.5 KiB
Python
"""FastAPI application: JSON API plus static hosting for the built frontend."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
from contextlib import asynccontextmanager
|
||
|
||
from fastapi import FastAPI, Request
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from fastapi.responses import FileResponse, JSONResponse
|
||
from fastapi.staticfiles import StaticFiles
|
||
|
||
from .config import MAX_BODY_BYTES, WEB_DIST
|
||
from . import config
|
||
from .db import init_db
|
||
from .routers import backup, content, flows, graph
|
||
from .seed import seed
|
||
|
||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)-7s %(name)s: %(message)s")
|
||
logger = logging.getLogger("it.panorama")
|
||
|
||
|
||
@asynccontextmanager
|
||
async def lifespan(app: FastAPI):
|
||
init_db()
|
||
conn = None
|
||
from .db import connect
|
||
from .services import metrics
|
||
|
||
conn = connect()
|
||
try:
|
||
if seed(conn):
|
||
logger.info("数据库首次初始化完成,已写入内置系统清单与数据流。")
|
||
metrics.ensure_history(conn)
|
||
finally:
|
||
conn.close()
|
||
logger.info("SQLite: %s", config.db_path())
|
||
yield
|
||
|
||
|
||
app = FastAPI(
|
||
title="公司 IT 系统全景与数据流向平台",
|
||
version="1.0.0",
|
||
description="IT 系统清单、数据流向图与流量指标的统一可配置后端。",
|
||
lifespan=lifespan,
|
||
)
|
||
|
||
app.add_middleware(
|
||
CORSMiddleware,
|
||
allow_origins=["*"],
|
||
allow_credentials=False,
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
)
|
||
|
||
|
||
@app.middleware("http")
|
||
async def limit_body_size(request: Request, call_next):
|
||
"""Guard the import endpoint before the body is buffered in memory."""
|
||
declared = request.headers.get("content-length")
|
||
if declared and request.method in {"POST", "PUT", "PATCH"} and int(declared) > MAX_BODY_BYTES:
|
||
return JSONResponse({"detail": "请求体过大"}, status_code=413)
|
||
return await call_next(request)
|
||
|
||
|
||
app.include_router(content.router)
|
||
app.include_router(flows.router)
|
||
app.include_router(graph.router)
|
||
app.include_router(backup.router)
|
||
|
||
|
||
@app.get("/api/health")
|
||
def health() -> dict:
|
||
return {"ok": True, "db": str(config.db_path())}
|
||
|
||
|
||
# ---------------------------------------------------------------- static frontend
|
||
|
||
if WEB_DIST.is_dir():
|
||
app.mount("/assets", StaticFiles(directory=WEB_DIST / "assets"), name="assets")
|
||
|
||
@app.get("/favicon.ico", include_in_schema=False)
|
||
def favicon():
|
||
path = WEB_DIST / "favicon.ico"
|
||
return FileResponse(path) if path.is_file() else JSONResponse({}, status_code=404)
|
||
|
||
@app.get("/{full_path:path}", include_in_schema=False)
|
||
def spa(full_path: str):
|
||
"""History-mode routing means unknown paths must fall back to index.html."""
|
||
if full_path.startswith("api/"):
|
||
# A typo in an API path must not masquerade as a successful page load.
|
||
return JSONResponse({"detail": "接口不存在"}, status_code=404)
|
||
candidate = (WEB_DIST / full_path).resolve()
|
||
if full_path and candidate.is_file() and candidate.is_relative_to(WEB_DIST.resolve()):
|
||
return FileResponse(candidate)
|
||
return FileResponse(WEB_DIST / "index.html")
|
||
|
||
else:
|
||
|
||
@app.get("/", include_in_schema=False)
|
||
def missing_frontend() -> JSONResponse:
|
||
return JSONResponse(
|
||
{
|
||
"detail": "前端尚未构建。请在 ../frontend 执行 pnpm install && pnpm build,"
|
||
"或使用 pnpm dev(默认 http://localhost:5273,已代理 /api 到本服务)。"
|
||
},
|
||
status_code=200,
|
||
)
|