Files
DecomEval/backend/app/main.py
T
nixevol 85ac243ea1 feat: 退网评估后端:单个或清单提交,按逻辑站点并行评估并写入固定模板
每个逻辑站点一个排队任务,与采集共用并行数量;工参按拆除前后规则取本系统快照,指标暂用模拟数据;全部站点结束后写频段清退、低效拆除两份结果表。去掉原来的通用导出任务。
2026-11-11 03:25:38 +08:00

86 lines
2.8 KiB
Python

from __future__ import annotations
import logging
import re
from pathlib import Path
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from app.api.evaluate import router as evaluate_router
from app.api.http import router
from app.auth.platform import base_href
from app.bootstrap import init_db
from app.config import installed
logger = logging.getLogger("decom")
WEB_DIST = next(
(
candidate
for candidate in (
Path(__file__).resolve().parents[2] / "web" / "dist",
Path(__file__).resolve().parents[1] / "web" / "dist",
)
if (candidate / "index.html").is_file()
),
Path(__file__).resolve().parents[2] / "web" / "dist",
)
BASE_TAG = re.compile(r"<base\b[^>]*>", re.IGNORECASE)
@asynccontextmanager
async def lifespan(_application: FastAPI):
init_db()
yield
def render_index(html: str, href: str) -> str:
tag = f'<base href="{href}" />'
if BASE_TAG.search(html):
return BASE_TAG.sub(tag, html, count=1)
return html.replace("<head>", f"<head>\n {tag}", 1)
def create_app(web_dist: Path | None = None) -> FastAPI:
logging.basicConfig(level=logging.INFO)
application = FastAPI(title="DecomEval", lifespan=lifespan)
application.include_router(router)
application.include_router(evaluate_router)
dist = (web_dist or WEB_DIST).resolve()
@application.middleware("http")
async def require_install(request, call_next):
path = request.url.path
if path.startswith("/api/") and not path.startswith("/api/install") and not installed():
return JSONResponse({"detail": "尚未安装"}, status_code=503)
return await call_next(request)
if (dist / "index.html").is_file():
if (dist / "assets").is_dir():
application.mount("/assets", StaticFiles(directory=dist / "assets"), name="assets")
def index(request: Request) -> HTMLResponse:
html = (dist / "index.html").read_text(encoding="utf-8")
return HTMLResponse(
render_index(html, base_href(request.headers)),
headers={"Cache-Control": "no-store", "Vary": "X-Forwarded-Prefix"},
)
@application.get("/{path:path}", response_model=None)
def pages(path: str, request: Request) -> FileResponse | HTMLResponse:
if path == "api" or path.startswith("api/"):
raise HTTPException(status_code=404, detail="接口不存在")
if path and path != "index.html":
target = (dist / path).resolve()
if target.is_file() and target.is_relative_to(dist):
return FileResponse(target)
return index(request)
return application
app = create_app()