From 4fb8f6447cea84b5b934f5a6e99fdbc24f190bc1 Mon Sep 17 00:00:00 2001 From: guke Date: Mon, 29 Jun 2026 12:51:42 +0800 Subject: [PATCH] =?UTF-8?q?feat(h5):=20FastAPI=20StaticFiles=20=E5=90=8C?= =?UTF-8?q?=E6=BA=90=E6=89=98=E7=AE=A1=20/h5(.html=20no-cache)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.8 (1M context) --- app/main.py | 17 +++++++++++++++++ tests/test_h5_hosting.py | 14 ++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 tests/test_h5_hosting.py diff --git a/app/main.py b/app/main.py index 7b5e376..902c1b2 100644 --- a/app/main.py +++ b/app/main.py @@ -142,3 +142,20 @@ app.mount( StaticFiles(directory=str(_media_root)), name="media", ) + +# 业务 H5 同源托管(/h5)。与 /api/v1 同 host → H5 用相对路径调后端,免 CORS。 +# .html 加 no-cache:后端改完用户重开页即拉新(远程热更核心);js/图片走默认缓存。 +class _NoCacheHTMLStaticFiles(StaticFiles): + async def get_response(self, path: str, scope): + resp = await super().get_response(path, scope) + if path.endswith(".html"): + resp.headers["Cache-Control"] = "no-cache" + return resp + + +_h5_root = Path(__file__).resolve().parent.parent / "h5" +app.mount( + "/h5", + _NoCacheHTMLStaticFiles(directory=str(_h5_root), html=True), + name="h5", +) diff --git a/tests/test_h5_hosting.py b/tests/test_h5_hosting.py new file mode 100644 index 0000000..76eeff4 --- /dev/null +++ b/tests/test_h5_hosting.py @@ -0,0 +1,14 @@ +"""H5 静态托管冒烟:/h5 同源服务页面 + .html no-cache(热更核心)。""" +from __future__ import annotations + + +def test_h5_shared_bridge_served(client) -> None: + resp = client.get("/h5/shared/bridge.js") + assert resp.status_code == 200 + + +def test_h5_html_no_cache(client) -> None: + # records 迁入前,先用已在仓库的 mine 页验证 .html 的 no-cache 响应头 + resp = client.get("/h5/mine/index.html") + assert resp.status_code == 200 + assert resp.headers.get("cache-control") == "no-cache"