虽然公司很多采用前后端分离,还是了解下FastAPI渲染模板
参考官网:https://fastapi.tiangolo.com/advanced/templates/
安装fastapi, jinja2
官网代码
from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") @app.get("/items/{id}", response_class=HTMLResponse) async def read_item(request: Request, id: str): return templates.TemplateResponse("item.html", {"request": request, "id": id}) if __name__ == '__main__': import uvicorn uvicorn.run(app, host="localhost", port=8080)
需要创建templates和static文件夹
item.html
<html> <head> <title>item index.html</title> </head> <body> <h1>Item ID: {{ id }}</h1> </body> </html>