FastAPI依赖注入系统及调试技巧
title: FastAPI依赖注入系统及调试技巧


from fastapi import Depends, FastAPI
app = FastAPI()
# 第一层依赖:数据库连接
async def get_db():
print("Connecting to database...")
yield "DatabaseConnection"
print("Closing database connection...")
# 第二层依赖:用户认证
async def auth_user(db: str = Depends(get_db)):
print(f"Authenticating user with {db}")
return {"user": "admin", "role": "superuser"}
# 第三层依赖:权限验证
async def check_permissions(user: dict = Depends(auth_user)):
if user["role"] != "superuser":
raise HTTPException(status_code=403)
return {"permissions": ["read", "write"]}
@app.get("/data")
async def get_data(perms: dict = Depends(check_permissions)):
return {"message": "Secret data", "perms": perms}
# 在启动命令后添加参数显示路由依赖
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000, debug=True)
pip install pydeps
pydeps your_module:app --show-deps
# 错误示例:循环依赖
async def dependency_a(b: str = Depends(dependency_b)):
return "A"
async def dependency_b(a: str = Depends(dependency_a)):
return "B"
@app.get("/circular")
async def circular_route(a: str = Depends(dependency_a)):
return {"a": a}
评论
发表评论