當(dāng)前位置:首頁(yè) > IT技術(shù) > Windows編程 > 正文

FastAPI使用jinja2 渲染模板
2021-08-07 11:05:39

雖然公司很多采用前后端分離,還是了解下FastAPI渲染模板

參考官網(wǎng):https://fastapi.tiangolo.com/advanced/templates/

安裝fastapi, jinja2

官網(wǎng)代碼

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)

需要?jiǎng)?chuàng)建templates和static文件夾

item.html

<html>
    <head>
        <title>item index.html</title>
    </head>
    <body>
        <h1>Item ID: {{ id }}</h1>
    </body>
</html>

FastAPI使用jinja2 渲染模板_ico

?

本文摘自 :https://blog.51cto.com/u

開通會(huì)員,享受整站包年服務(wù)立即開通 >