50 lines
1.6 KiB
Python
50 lines
1.6 KiB
Python
"""__TITLE__: FastAPI backend serving a no-build static frontend from app/static."""
|
|
|
|
import contextlib
|
|
import os
|
|
from pathlib import Path
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.responses import FileResponse
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
from app import api
|
|
|
|
VERSION = os.environ.get("APP_VERSION", "dev")
|
|
STATIC = Path(__file__).parent / "static"
|
|
DATA_DIR = Path(os.environ.get("DATA_DIR", "data"))
|
|
|
|
|
|
@contextlib.asynccontextmanager
|
|
async def lifespan(_app: FastAPI):
|
|
# Startup work goes here, not at import time: `update` imports this module as a check
|
|
# before restarting. Create tables or run migrations idempotently here.
|
|
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
|
yield
|
|
|
|
|
|
app = FastAPI(title="__TITLE__", version=VERSION, lifespan=lifespan, docs_url="/api/docs", redoc_url=None, openapi_url="/api/openapi.json")
|
|
app.include_router(api.router, prefix="/api")
|
|
|
|
|
|
@app.get("/healthz", include_in_schema=False)
|
|
def healthz() -> dict:
|
|
# `update` waits for this to report the new commit before it calls the update done.
|
|
return {"status": "ok", "version": VERSION}
|
|
|
|
|
|
class Assets(StaticFiles):
|
|
"""Browsers revalidate on every load (cheap 304s), so an update shows up at once."""
|
|
|
|
async def get_response(self, path, scope):
|
|
response = await super().get_response(path, scope)
|
|
response.headers["Cache-Control"] = "no-cache"
|
|
return response
|
|
|
|
|
|
app.mount("/static", Assets(directory=STATIC), name="static")
|
|
|
|
|
|
@app.get("/", include_in_schema=False)
|
|
def index() -> FileResponse:
|
|
return FileResponse(STATIC / "index.html", headers={"Cache-Control": "no-cache"})
|