Skip to content

Instantly share code, notes, and snippets.

@SpotlightKid
Last active March 22, 2024 18:18
Show Gist options
  • Save SpotlightKid/1effeaf2442905bcdf29ba2f91f2c976 to your computer and use it in GitHub Desktop.
Save SpotlightKid/1effeaf2442905bcdf29ba2f91f2c976 to your computer and use it in GitHub Desktop.
Basic FastAPI app template with Jinja2 templating and static files
"""Template for a minimal FastAPI app serving just one page from a Jinja2 template and a favicon.
Place the Jinja2 "index.html" template in "templates/jinja2" and a "favicon.ico" icon file in
"static/img" and additional static files (JavaScript, CSS, images) below "static". You can then
reference them in the template like this ("path" is relative to "static"):
{{ url_for('static', path='/dir/file.txt') }}
"""
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, status
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
app.add_middleware(GZipMiddleware, minimum_size=1000)
templates = Jinja2Templates(directory="templates/jinja2")
@asynccontextmanager
async def lifespan(app: FastAPI):
print("Initialising app...")
yield
print("shutting down app...")
app.router.lifespan_context = lifespan
@app.get("/", response_class=HTMLResponse)
async def index(req: Request):
return templates.TemplateResponse(request=req, name="index.html")
@app.get("/favicon.ico")
async def favicon(req: Request):
return RedirectResponse(
req.url_for("static", path="/img/favicon.ico"),
status_code=status.HTTP_301_MOVED_PERMANENTLY,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment