用 FastAPI 打造智慧網站:解鎖會話管理的魔法
你是否曾在電商網站上納悶:為什麼登錄一次後,網站就能「記住」我是誰?為什麼購物車裡的商品不會因為換頁而消失?這背後的秘密就是 會話管理 (Session Management)!今天,我們將使用 Python 最酷的 Web 框架 FastAPI,教你實現這個功能,讓你的網站更聰明、更人性化!
完整程式碼:GitHub 倉庫
適合人群:Python 初學者、Web 開發新手、對會話管理好奇的你!
什麼是會話管理?為什麼重要?
想像你走進一家商店,店員遞給你一個購物籃,並記住你是「小明」。即使你逛到不同貨架,店員依然知道你的籃子裡有什麼。這就是會話管理的概念!
在網站中,瀏覽器和伺服器的每次通訊都是「無狀態的」——伺服器處理完請求後會「失憶」。如果沒有會話管理,你得在每個頁面重複輸入帳號密碼,購物車也會變成「空籃子」。會話管理讓伺服器能:
- 記住你的身份:保持登錄狀態。
- 儲存購物車:記錄你添加的商品。
- 個人化體驗:記住你的偏好(如深色模式)。
運作原理:伺服器為你生成一個唯一的「會話 ID」,存進瀏覽器的 Cookie。每次請求,Cookie 會自動附上,伺服器就能認出你並調出你的資料。
FastAPI 的會話魔法:SessionMiddleware
FastAPI 借助 Starlette 的 SessionMiddleware
,讓會話管理變得超簡單。它會:
- 生成唯一的會話 ID。
- 將 ID 儲存在安全的 Cookie 中。
- 每次請求時,根據 Cookie 中的 ID 讀取或更新會話資料。
動手實作:打造你的 FastAPI 會話應用
讓我們用一個簡單的範例,實現登錄、登出和購物車功能。完整程式碼在 GitHub。
步驟 1:設置環境
- 複製專案:
git clone https://github.com/BpsEason/fastapi-session-management.git cd fastapi-session-management
- 安裝依賴:
專案包含
requirements.txt
,列出以下依賴:fastapi==0.111.0
uvicorn[standard]==0.30.1
python-dotenv==1.0.1
starlette==0.37.2
安裝命令:
pip install -r requirements.txt
- 設置秘密金鑰:
會話安全依賴一個隨機的
SECRET_KEY
。在專案根目錄創建.env
文件:SECRET_KEY=your_very_long_and_random_secret_key_here
生成金鑰:
python import secrets print(secrets.token_urlsafe(32))
將生成的字串貼到
.env
中。注意:切勿硬編碼或上傳到 GitHub!.gitignore
已確保.env
不會被提交。
步驟 2:核心程式碼解析
專案的 main.py
包含了會話管理的實現。以下是關鍵片段(完整程式碼見 GitHub):
from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware
from dotenv import load_dotenv
import os
# 載入環境變數
load_dotenv()
SECRET_KEY = os.getenv("SECRET_KEY") or raise ValueError("請設定 .env 中的 SECRET_KEY")
app = FastAPI()
# 設置會話中間件
app.add_middleware(
SessionMiddleware,
secret_key=SECRET_KEY,
secure=False, # 生產環境設為 True(需 HTTPS)
httponly=True, # 防止 XSS 攻擊
samesite="lax", # 防止 CSRF 攻擊
max_age=3600 # 會話有效期 1 小時
)
# 首頁
@app.get("/")
async def read_root():
return {"message": "歡迎體驗 FastAPI 會話管理!"}
# 模擬登錄
@app.post("/login")
async def login(request: Request):
request.session["logged_in"] = True
request.session["username"] = "學習者小明"
return {"message": "您已成功登入!"}
# 查看用戶狀態
@app.get("/me")
async def get_current_user(request: Request):
if request.session.get("logged_in"):
username = request.session.get("username")
return {"message": f"您好,{username}!您目前已登入。", "is_logged_in": True}
return {"message": "您尚未登入。", "is_logged_in": False}
# 登出
@app.post("/logout")
async def logout(request: Request):
request.session.clear()
return {"message": "您已成功登出!"}
# 查看購物車
@app.get("/cart")
async def get_cart(request: Request):
cart_items = request.session.get("cart", [])
return {"message": "您的購物車內容:", "items": cart_items}
# 添加商品
@app.post("/cart/add")
async def add_to_cart(request: Request, item_name: str):
cart_items = request.session.get("cart", [])
cart_items.append(item ✨
System: The response was cut off because it exceeded the maximum allowed length. Below is the completion of the HTML-optimized article for Blogger, continuing from where it was truncated, ensuring proper formatting and compatibility with Blogger's editor. I'll also include steps to fix formatting issues and ensure your FastAPI session management tutorial displays correctly on your Blogger blog.
---
cart_items.append(item_name)
request.session["cart"] = cart_items
return {"message": f"'{item_name}' 已加入購物車!", "current_cart": cart_items}
程式碼亮點:
- 環境變數:使用
python-dotenv
安全載入SECRET_KEY
。 - SessionMiddleware:配置
httponly=True
和samesite="lax"
,增強安全性。 - API 端點:模擬真實應用場景(登錄、購物車),簡單易懂。
- 會話有效期:設定為 1 小時,確保不過度佔用資源。
步驟 3:運行與測試
- 啟動應用:
uvicorn main:app --reload
應用將運行在
http://127.0.0.1:8000
。訪問http://127.0.0.1:8000/docs
查看 FastAPI 的互動式 API 文件(Swagger UI)。 - 測試流程:
使用 Swagger UI 測試以下端點:
端點 方法 描述 範例回應 /
GET 顯示歡迎訊息 {"message": "歡迎體驗 FastAPI 會話管理!"}
/me
GET 查看用戶狀態 {"message": "您尚未登入。", "is_logged_in": false}
或{"message": "您好,學習者小明!您目前已登入。", "is_logged_in": true}
/login
POST 模擬登錄 {"message": "您已成功登入!"}
/logout
POST 登出並清除會話 {"message": "您已成功登出!"}
/cart
GET 查看購物車 {"message": "您的購物車內容:", "items": ["蘋果"]}
/cart/add
POST 添加商品 {"message": "'蘋果' 已加入購物車!", "current_cart": ["蘋果"]}
測試步驟:
- 訪問
GET /me
,確認未登入狀態。 - 執行
POST /login
,模擬登入。 - 再次訪問
GET /me
,確認顯示「學習者小明」。 - 執行
POST /cart/add
(輸入「蘋果」)。 - 訪問
GET /cart
,查看購物車內容。 - 執行
POST /logout
,登出。 - 再次訪問
GET /me
,確認已登出。
安全性必知
會話管理涉及敏感資料,安全性至關重要:
- HTTPS 必須:生產環境中,將
secure=True
並使用 SSL 證書(如 Let’s Encrypt)加密通訊。 - 保護 SECRET_KEY:儲存在
.env
,切勿硬編碼或公開。 - 防止 XSS:
httponly=True
確保 Cookie 不被 JavaScript 存取。 - 防止 CSRF:
samesite="lax"
降低跨站請求偽造風險。 - 會話有效期:預設 1 小時(
max_age=3600
),可調整。
下一步:讓你的專案更強大
完成這個範例後,你可以嘗試:
- 資料庫整合:用 SQLite 或 PostgreSQL 實現真實用戶認證。
- 前端介面:搭配 React 或 Vue.js 打造互動式體驗。
- 單元測試:使用
pytest
和 FastAPI 的TestClient
確保程式碼穩定。 - 自動化部署:透過 GitHub Actions 或 Docker 部署到雲端。
立即開始!
快來試試這個簡單又實用的 FastAPI 會話管理範例!複製程式碼、運行應用,體驗伺服器如何「記住」你的狀態。完整程式碼和說明在 GitHub。有問題?歡迎在 GitHub 提交 Issue 或在下方留言!
小提示:想深入學習?試著添加刪除購物車商品的功能,或實現多用戶支援,讓你的網站更像真正的電商平台!
沒有留言:
張貼留言