Depends
FastAPI有一個非常強大但直觀的依賴注入系統。
它的設計使用起來非常簡單,並使任何開發人員都可以非常輕松地將其他組件與FastAPI集成在一起。
什么是“依賴注入”
“依賴注入”是指在編程中,您的代碼(在這種情況下,您的路徑操作函數)有一種方法可以聲明它需要工作和使用的東西:“依賴”。
然后,該系統(在本例中為FastAPI)將完成為代碼提供所需依賴項(“注入”依賴項)所需的一切。
當您需要:
- 有共享邏輯(一次又一次地使用相同的代碼邏輯)。
- 共享數據庫連接。
- 強制執行安全性,身份驗證,角色要求等。
- 還有很多其他事情
from typing import Optional from fastapi import Depends, FastAPI app = FastAPI() async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: dict = Depends(common_parameters)): return commons
https://fastapi.tiangolo.com/tutorial/dependencies/#integrated-with-openapi