diff --git a/app/web/routes.py b/app/web/routes.py index e28180c..87e86c8 100644 --- a/app/web/routes.py +++ b/app/web/routes.py @@ -1,5 +1,8 @@ from __future__ import annotations +import hashlib +from pathlib import Path + from fastapi import APIRouter, Request from fastapi.templating import Jinja2Templates @@ -9,6 +12,23 @@ router = APIRouter() templates = Jinja2Templates(directory="app/web/templates") +def _asset_version(path: str) -> str: + """A short hash of a static asset's content, used to cache-bust it in + templates -- browsers apply much more aggressive heuristic caching to + linked CSS/JS than to the dynamically-rendered HTML that references it, + so without this, a deploy that only changes style.css can leave a + visitor's browser silently serving the old stylesheet until they + hard-refresh. Computed once at startup since the file is baked into the + image and won't change while this process is running.""" + try: + return hashlib.md5(Path(path).read_bytes()).hexdigest()[:8] + except FileNotFoundError: + return "0" + + +templates.env.globals["static_version"] = _asset_version("app/static/css/style.css") + + @router.get("/") def dashboard(request: Request): return templates.TemplateResponse(request, "dashboard.html", {}) diff --git a/app/web/templates/base.html b/app/web/templates/base.html index 9fccdd0..457895e 100644 --- a/app/web/templates/base.html +++ b/app/web/templates/base.html @@ -5,7 +5,7 @@ Power Compare - +