
- 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 內建的依賴注入系統使得在構建 API 時更容易整合元件。在程式設計中,**依賴注入**指的是一個物件接收其依賴的其他物件的一種機制。這些其他物件稱為依賴項。依賴注入具有以下優點:
重用相同的共享邏輯
共享資料庫連線
強制執行身份驗證和安全功能
假設一個 FastAPI 應用有兩個操作函式,它們都具有相同的查詢引數 id、name 和 age。
from fastapi import FastAPI app = FastAPI() @app.get("/user/") async def user(id: str, name: str, age: int): return {"id": id, "name": name, "age": age} @app.get("/admin/") async def admin(id: str, name: str, age: int): return {"id": id, "name": name, "age": age}
如果需要進行任何更改,例如新增/刪除查詢引數,則需要更改兩個路由裝飾器和函式。
FastAPI 提供了**Depends**類,其物件在這種情況下用作通用引數。首先從 FastAPI 中匯入**Depends**並定義一個函式來接收這些引數:
async def dependency(id: str, name: str, age: int): return {"id": id, "name": name, "age": age}
現在,我們可以將此函式的返回值用作操作函式中的引數。
@app.get("/user/") async def user(dep: dict = Depends(dependency)): return dep
對於每個新的請求,FastAPI 使用相應的引數呼叫依賴函式,返回結果,並將結果分配給您的操作。
您可以使用類來管理依賴項而不是函式。宣告一個類,其中 id、name 和 age 作為屬性。
class dependency: def __init__(self, id: str, name: str, age: int): self.id = id self.name = name self.age = age
將此類用作引數的型別。
@app.get("/user/") async def user(dep: dependency = Depends(dependency)): return dep @app.get("/admin/") async def admin(dep: dependency = Depends(dependency)): return dep
在這裡,我們在操作函式中使用了依賴注入。它也可以用作操作裝飾器。例如,我們想檢查查詢引數 age 的值是否小於 21。如果是,則應丟擲異常。因此,我們編寫一個函式來檢查它並將其用作依賴項。
async def validate(dep: dependency = Depends(dependency)): if dep.age > 18: raise HTTPException(status_code=400, detail="You are not eligible") @app.get("/user/", dependencies=[Depends(validate)]) async def user(): return {"message": "You are eligible"}
在 FastAPI 依賴項管理中,您可以使用 yield 而不是 return 來新增一些額外的步驟。例如,以下函式使用帶有 yield 的資料庫依賴項。
async def get_db(): db = DBSession() try: yield db finally: db.close()
廣告