Files
nixevol 4fb44ab27a feat: 管理界面新增数据浏览页(服务端分页)
- 新增「数据」页:按制式筛选、CGI/小区名称搜索、四种排序,每页 20/50/100 条,数据库端 LIMIT/OFFSET 分页,越界页自动回退到最后一页
- 点击行查看详情:基础字段与 1 公里内高干扰小区数的本期/上期分制式对比
- 首次打开该页才加载,新批次入库后自动刷新;加载中状态与过期请求丢弃,避免界面卡顿
- 新增 GET /api/data 接口(仅管理员),读取失败返回 502
- MySQL 直连与 Metrix 接口两种模式都支持只读查询,接口模式浏览查询超时 20 秒;两种模式数值格式统一
- 搜索词转义引号与 LIKE 通配符,制式、排序、页大小走白名单
- 补充单元测试与中英文文案
2026-11-06 18:02:36 +08:00

153 lines
5.1 KiB
Python

from __future__ import annotations
import logging
import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Any
from fastapi import Body, Depends, FastAPI, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
from .auth import Identity, require_admin
from .config import SettingsError, data_dir, public_view
from .data import DataQuery
from .service import EtlService
LANDING_HTML = """<!doctype html>
<html><head><meta charset="utf-8"><title>InterferenceETL</title>
<script>location.replace(location.pathname.replace(/\\/?$/, '/') + 'admin');</script>
</head><body><a href="admin">InterferenceETL</a></body></html>
"""
def settings_error(exc: SettingsError) -> JSONResponse:
return JSONResponse(status_code=422, content={"error": exc.key, "field": exc.field, "params": exc.params})
def build_api(service: EtlService) -> FastAPI:
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
service.start()
try:
yield
finally:
service.stop()
api = FastAPI(title="InterferenceETL", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
@api.get("/", include_in_schema=False)
def landing() -> HTMLResponse:
return HTMLResponse(LANDING_HTML)
@api.get("/healthz")
def health() -> dict[str, bool]:
return {"ok": True}
@api.get("/api/status")
def status(_: Identity = Depends(require_admin)) -> dict[str, Any]:
return service.status()
@api.get("/api/settings")
def read_settings(_: Identity = Depends(require_admin)) -> dict[str, Any]:
return public_view(service.settings.get())
@api.put("/api/settings", response_model=None)
def write_settings(payload: dict[str, Any] = Body(...), _: Identity = Depends(require_admin)) -> Any:
try:
return public_view(service.update_settings(payload))
except SettingsError as exc:
return settings_error(exc)
@api.post("/api/checks", response_model=None)
def checks(payload: dict[str, Any] | None = Body(None), _: Identity = Depends(require_admin)) -> Any:
try:
return service.check_connections(payload)
except SettingsError as exc:
return settings_error(exc)
@api.get("/api/runs")
def runs(page: int = 1, page_size: int = 20, status: str = "", _: Identity = Depends(require_admin)) -> dict[str, Any]:
items, total = service.runs.page(max(1, page), min(max(1, page_size), 200), status)
return {"items": items, "total": total}
@api.post("/api/runs")
def start_run(payload: dict[str, Any] | None = Body(None), _: Identity = Depends(require_admin)) -> dict[str, bool]:
if not service.settings.configured():
raise HTTPException(status_code=409, detail="not_configured")
if not service.runner.start("manual", bool((payload or {}).get("dry_run"))):
raise HTTPException(status_code=409, detail="busy")
return {"started": True}
@api.post("/api/runs/cancel")
def cancel_run(_: Identity = Depends(require_admin)) -> dict[str, bool]:
return {"cancelled": service.runner.cancel()}
@api.get("/api/data", response_model=None)
def data(
page: int = 1,
page_size: int = 20,
network: str = "",
q: str = "",
sort: str = "interference",
_: Identity = Depends(require_admin),
) -> Any:
query = DataQuery(page=page, page_size=page_size, network=network, keyword=q, sort=sort)
try:
return service.data.browse(query)
except Exception as exc:
return JSONResponse(status_code=502, content={"error": "data_unavailable", "detail": str(exc)[:500]})
@api.get("/api/runs/{run_id}/log", response_class=PlainTextResponse)
def run_log(run_id: int, _: Identity = Depends(require_admin)) -> str:
if service.runs.get(run_id) is None:
raise HTTPException(status_code=404, detail="not_found")
return service.runner.read_log(run_id)
return api
def create_app() -> FastAPI:
from nicegui import ui
from .theme import ICON_PATH
from .ui import register
service = EtlService(data_dir())
api = build_api(service)
register(service)
ui.run_with(
api,
title="InterferenceETL",
favicon=ICON_PATH,
dark=None,
language="zh-CN",
reconnect_timeout=10,
show_welcome_message=False,
)
return api
class QuietSockets(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
message = record.getMessage()
return not (message.startswith("connection ") or '"WebSocket ' in message)
def main() -> None:
import uvicorn
config = uvicorn.Config(
create_app(),
host=os.getenv("HOST", "0.0.0.0"),
port=int(os.getenv("PORT", "8080")),
access_log=False,
timeout_graceful_shutdown=15,
)
logging.getLogger("uvicorn.error").addFilter(QuietSockets())
uvicorn.Server(config).run()
if __name__ == "__main__":
main()