from __future__ import annotations import logging from pathlib import Path from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.responses import FileResponse, JSONResponse from fastapi.staticfiles import StaticFiles from app.api.http import router from app.bootstrap import init_db from app.config import installed from app.runtime import start_background 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", ) @asynccontextmanager async def lifespan(_application: FastAPI): init_db() start_background() yield def create_app() -> FastAPI: logging.basicConfig(level=logging.INFO) application = FastAPI(title="DecomEval", lifespan=lifespan) application.include_router(router) @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 (WEB_DIST / "index.html").is_file(): application.mount("/assets", StaticFiles(directory=WEB_DIST / "assets"), name="assets") @application.get("/{path:path}") def pages(path: str) -> FileResponse: target = WEB_DIST / path if path and target.is_file(): return FileResponse(target) return FileResponse(WEB_DIST / "index.html") return application app = create_app()