- FastAPI 教程
- FastAPI - 首頁
- FastAPI - 簡介
- FastAPI - Hello World
- FastAPI - OpenAPI
- FastAPI - Uvicorn
- FastAPI - 型別提示
- FastAPI - IDE 支援
- FastAPI - REST 架構
- FastAPI - 路徑引數
- FastAPI - 查詢引數
- FastAPI - 引數驗證
- FastAPI - Pydantic
- FastAPI - 請求體
- FastAPI - 模板
- FastAPI - 靜態檔案
- FastAPI - HTML 表單模板
- FastAPI - 訪問表單資料
- FastAPI - 上傳檔案
- FastAPI - Cookie 引數
- FastAPI - 頭部引數
- FastAPI - 響應模型
- FastAPI - 巢狀模型
- FastAPI - 依賴項
- FastAPI - CORS
- FastAPI - CRUD 操作
- FastAPI - SQL 資料庫
- FastAPI - 使用 MongoDB
- FastAPI - 使用 GraphQL
- FastAPI - WebSockets
- FastAPI - FastAPI 事件處理器
- FastAPI - 掛載子應用
- FastAPI - 中介軟體
- FastAPI - 掛載 Flask 應用
- FastAPI - 部署
- FastAPI 有用資源
- FastAPI - 快速指南
- FastAPI - 有用資源
- FastAPI - 討論
FastAPI - 中介軟體
中介軟體是一個函式,它會在每個請求處理之前(在任何特定路徑操作處理之前)以及在返回每個響應之前進行處理。此函式接收進入應用程式的每個請求。它可以透過執行其中定義的程式碼對請求執行某些過程,然後將請求傳遞給相應的操作函式進行處理。它還可以處理操作函式生成的響應,然後再返回該響應。
以下是 FastAPI 庫中提供的一些中介軟體:
CORSMiddleware
HTTPSRedirectMiddleware
TrustedHostMiddleware
GZipMiddleware
FastAPI 提供了app.add_middleware() 函式來處理伺服器錯誤和自定義異常處理器。除了上述整合的中介軟體之外,還可以定義自定義中介軟體。以下示例定義了addmiddleware() 函式,並透過使用@app.middleware() 裝飾器將其裝飾為中介軟體。
該函式有兩個引數:HTTP 請求物件和call_next() 函式,該函式會將 API 請求傳送到其對應的路徑並返回響應。
除了中介軟體函式之外,應用程式還有兩個操作函式。
import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def addmiddleware(request: Request, call_next):
print("Middleware works!")
response = await call_next(request)
return response
@app.get("/")
async def index():
return {"message":"Hello World"}
@app.get("/{name}")
async def hello(name:str):
return {"message":"Hello "+name}
當應用程式執行時,對於瀏覽器發出的每個請求,中介軟體輸出(Middleware works!)將出現在控制檯日誌中,然後再出現響應輸出。
廣告