ここまでくると、Flask 、 django なんかなくたって、FastAPI で事足りる気がしてきた、
静的Webページアクセスの為の static 等は、
例えば、以下のディレクトリ構成である場合
root
├─ main.py
│
├─static
│
├─ templates
├─ index.html
main.py
from fastapi import FastAPI, Request, Path from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates import pathlib app = FastAPI() app.mount(path="/static", app=StaticFiles(directory=pathlib.Path(__file__).resolve().parent / "static"), name="static") templates = Jinja2Templates(directory=pathlib.Path(__file__).resolve().parent / "templates") @app.get(path="/", response_class=HTMLResponse) async def read_root(request: Request): context = {"request": request} return templates.TemplateResponse("index.html", context) async def view(id: int=Path(gt=0, lt=12, description="view対象のID")): # TODO view結果生成 return {"viewid": id }
import pathlib の Path と fastapi の Path が被らないように、
pathlib.Path(__file__).resolve().parent で絶対PATHを求めて使用するようにする必要がある。