樣板引擎
FastAPI 可以透過 `Jinja2Templates` 使用 Jinja2 樣板引擎,將後端資料嵌入 HTML,再以 HTML 回應給瀏覽器。
以下是一個「輸入兩個數字並計算乘積」的完整範例。
## 1. 安裝套件
```bash
pip install fastapi uvicorn jinja2 python-multipart
```
其中:
- `jinja2`:樣板引擎
- `python-multipart`:解析 HTML 表單資料所需
## 2. 專案結構
```text
project/
├── main.py
└── templates/
└── multiply.html
```
## 3. FastAPI 程式:`main.py`
```python
from fastapi import FastAPI, Request, Form
from fastapi.templating import Jinja2Templates
app = FastAPI()
# 指定 Jinja2 樣板所在的資料夾
templates = Jinja2Templates(directory="templates")
# 顯示表單
@app.get("/")
async def show_form(request: Request):
return templates.TemplateResponse(
request=request,
name="multiply.html",
context={
"a": None,
"b": None,
"result": None,
},
)
# 接收表單並計算乘法
@app.post("/multiply")
async def multiply(
request: Request,
a: int = Form(...),
b: int = Form(...),
):
result = a * b
return templates.TemplateResponse(
request=request,
name="multiply.html",
context={
"a": a,
"b": b,
"result": result,
},
)
```
## 4. Jinja2 樣板:`templates/multiply.html`
```html
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>乘法計算</title>
</head>
<body>
<h1>乘法計算器</h1>
<form method="post" action="/multiply">
<label>
第一個數字:
<input
type="number"
name="a"
value="{{ a if a is not none else '' }}"
required
>
</label>
<br><br>
<label>
第二個數字:
<input
type="number"
name="b"
value="{{ b if b is not none else '' }}"
required
>
</label>
<br><br>
<button type="submit">計算</button>
</form>
{% if result is not none %}
<h2>
{{ a }} × {{ b }} = {{ result }}
</h2>
{% endif %}
</body>
</html>
```
## 5. 啟動伺服器
在專案根目錄執行:
```bash
uvicorn main:app --reload
```
開啟瀏覽器前往:
```text
http://127.0.0.1:8000/
```
輸入:
```text
第一個數字:6
第二個數字:7
```
提交後,FastAPI 會計算:
```text
6 * 7 = 42
```
並將結果傳給 Jinja2,最後產生:
```html
<h2>6 × 7 = 42</h2>
```
## 執行流程
1. 使用者以 `GET /` 開啟網頁。
2. FastAPI 使用 `TemplateResponse` 載入 `multiply.html`。
3. 使用者在 HTML 表單輸入兩個數字。
4. 表單以 `POST /multiply` 傳送資料。
5. FastAPI 透過 `Form(...)` 取得表單欄位:
```python
a: int = Form(...)
b: int = Form(...)
```
6. 後端計算:
```python
result = a * b
```
7. 將 `a`、`b` 與 `result` 放入 `context`。
8. Jinja2 使用 `{{ ... }}` 將資料嵌入 HTML,回應給前端。
其中:
- `{{ result }}`:輸出變數內容
- `{% if result is not none %}`:Jinja2 條件判斷
- `context`:提供給樣板使用的資料字典
- `request`:使用 `TemplateResponse` 時通常需要傳入的請求物件
相關學習地圖、教學課程
Python 後端工程、資料庫