Files
DecomEval/backend/app/main.py
T

84 lines
2.7 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.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)
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()