Files
2026-11-05 15:07:45 +08:00

169 lines
6.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""FastAPI 应用工厂。
**默认关闭一切自动文档**(本项目接口说明写在 ``doc/API.md``,不需要 Swagger):
* ``FastAPI(docs_url=None, redoc_url=None, openapi_url=None)`` —— 不注册 /docs、/redoc、
/openapi.json 路由,也不生成 OpenAPI schema;
* 再把 ``/docs``、``/redoc``、``/swagger``、``/openapi.json`` 等常见探测路径显式占位成
**404 JSON**,返回统一错误体并提示去看 ``doc/API.md``(而不是框架的 404 页面);
* 只有显式设 ``SZ_ENABLE_DOCS=1`` 时才挂回 ``/docs``、``/redoc``、``/openapi.json``,
供内网临时调试。
前端只通过两个白名单入口提供:``/``(单页)与 ``/ui/<file>``(StaticFiles,本地 vue 等静态资源)。
"""
from __future__ import annotations
import logging
import os
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.staticfiles import StaticFiles
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.responses import FileResponse
from . import config
from .webjson import json_response
log = logging.getLogger("app")
UI_DIR = Path(__file__).resolve().parent / "static"
# 常见文档/调试路径:关闭时统一返回 404 JSON
_DOC_PATHS = ("/docs", "/doc", "/redoc", "/swagger", "/swagger-ui", "/openapi.json", "/api/docs")
_TRUTHY = {"1", "true", "yes", "on"}
def docs_enabled() -> bool:
"""是否打开自动文档。默认 **关闭**,需要时设环境变量 ``SZ_ENABLE_DOCS=1``。"""
return os.environ.get("SZ_ENABLE_DOCS", "").strip().lower() in _TRUTHY
def create_app() -> FastAPI:
enabled = docs_enabled()
@asynccontextmanager
async def lifespan(_app: FastAPI):
from .db import get_db
db = get_db() # 建表 + 连接预热
# 上一次进程被杀掉时可能留下"执行中"的僵尸任务,启动时统一收尾
for table in ("import_job", "export_job"):
db.execute(
f"UPDATE {table} SET status = 'failed', message = '服务重启,任务中断'"
" WHERE status IN ('pending', 'running')"
)
yield
app = FastAPI(
title="综资退网评估模板生成工具",
version="1.0.0",
description="工参/流量/需求清单入库并生成频段清退评估模板。接口说明见 doc/API.md。",
lifespan=lifespan,
# ↓ 三处一起为 None 才是真正关掉:不建路由、不生成 schema
docs_url="/docs" if enabled else None,
redoc_url="/redoc" if enabled else None,
openapi_url="/openapi.json" if enabled else None,
)
from .api import router
app.include_router(router)
# ---------------------------------------------------------------- 前端
@app.get("/", include_in_schema=False)
def index():
return FileResponse(UI_DIR / "index.html", media_type="text/html; charset=utf-8")
if UI_DIR.is_dir():
app.mount("/ui", StaticFiles(directory=UI_DIR), name="ui")
# ---------------------------------------------------------------- 健康检查
@app.get("/health", include_in_schema=False)
def health():
from .db import get_db as _get
try:
_get().scalar("SELECT 1")
db_ok = True
except Exception: # noqa: BLE001
db_ok = False
return json_response({"status": "ok" if db_ok else "degraded", "database": db_ok})
# ---------------------------------------------------------------- 屏蔽自动文档
if not enabled:
for path in _DOC_PATHS:
app.add_api_route(
path,
_blocked_handler(path),
methods=["GET"],
include_in_schema=False,
)
# ---------------------------------------------------------------- 上传大小
@app.middleware("http")
async def limit_upload(request: Request, call_next):
raw = request.headers.get("content-length")
limit = config.MAX_UPLOAD_MB * 1024 * 1024
if raw and raw.isdigit() and int(raw) > limit:
return json_response(
{
"error": {
"code": "payload_too_large",
"message": f"上传文件超过 {config.MAX_UPLOAD_MB}MB",
}
},
413,
)
return await call_next(request)
# ---------------------------------------------------------------- 错误处理
@app.exception_handler(StarletteHTTPException)
async def _http_error(request: Request, exc: StarletteHTTPException):
if exc.status_code == 404:
code, message = "not_found", f"资源不存在:{request.url.path}"
elif exc.status_code == 405:
code, message = "method_not_allowed", f"{request.method} 不被支持"
else:
code, message = "http_error", str(exc.detail or "请求失败")
return json_response({"error": {"code": code, "message": message}}, exc.status_code)
@app.exception_handler(RequestValidationError)
async def _validation_error(_request: Request, exc: RequestValidationError):
return json_response(
{"error": {"code": "bad_request", "message": f"请求参数不合法:{exc.errors()[:1]}"}},
400,
)
@app.exception_handler(Exception)
async def _unhandled(_request: Request, exc: Exception):
log.exception("unhandled error")
return json_response({"error": {"code": "internal_error", "message": str(exc)}}, 500)
return app
def _blocked_handler(path: str):
"""给每个文档路径生成一个返回 404 JSON 的处理函数。"""
async def blocked(_request: Request):
return json_response(
{
"error": {
"code": "not_found",
"message": f"{path} 未启用:本服务不提供自动生成的接口文档,"
"请查看 doc/API.md",
}
},
404,
)
blocked.__name__ = f"blocked_{path.strip('/').replace('/', '_').replace('.', '_')}"
return blocked
__all__ = ["create_app", "docs_enabled"]