是 FastAPI 提供的一个 函数(特殊的可调用对象),用于声明依赖注入(Dependency Injection,DI)。

数据库依赖注入

from fastapi import Depends

def get_db():
db = DBSession()
try:
yield db
finally:
db.close()

@app.get(“/items/”)
def read_items(db = Depends(get_db)):
return db.query(Item).all()

里的 db 参数 不是用户传的,而是 FastAPI 自动调用 get_db() 把结果注入。

鉴权或获取当前用户

from fastapi import Depends, HTTPException

def get_current_user(token: str):
if token != “secret”:
raise HTTPException(401, “Invalid Token”)
return {“username”: “admin”}

@app.get(“/userinfo”)
def userinfo(user = Depends(get_current_user)):
return user

不给 Depends 传函数(默认为 None)

from fastapi import Depends

@app.get(“/example”)
def example(dep = Depends()):
return {“msg”: “You used Depends() without function”}

通常用于和全局依赖、多层嵌套依赖配合,FastAPI 会自动解析依赖树。

为什么叫“依赖注入”?

因为参数值不是用户提供的,而是由“外部系统”自动注入进来的,这种模式称为 Dependency Injection(DI),是一种常见的软件架构设计模式。

作者 admin

百度广告效果展示