推荐答案
在 FastAPI 中,dependencies 参数用于在路径操作装饰器中注入依赖项。这些依赖项可以是函数、类或其他可调用对象,它们会在处理请求之前执行,并且可以返回一些数据或执行一些操作。
// www.javascriptcn.com code example
from fastapi import Depends, FastAPI, HTTPException
app = FastAPI()
def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/", dependencies=[Depends(common_parameters)])
async def read_items():
return {"message": "Hello World"}在这个例子中,common_parameters 函数被用作依赖项,并通过 dependencies 参数注入到 /items/ 路径操作中。当请求到达 /items/ 时,common_parameters 会首先执行,并返回一个包含查询参数的字典。
本题详细解读
1. 什么是 dependencies 参数?
dependencies 参数是 FastAPI 路径操作装饰器(如 @app.get、@app.post 等)中的一个可选参数。它允许你在处理请求之前注入一个或多个依赖项。这些依赖项可以是函数、类或其他可调用对象。
2. 如何使用 dependencies 参数?
你可以在路径操作装饰器中使用 dependencies 参数来指定一个依赖项列表。每个依赖项都应该是 Depends 的实例,Depends 是 FastAPI 提供的一个特殊类,用于声明依赖项。
@app.get("/items/", dependencies=[Depends(common_parameters)])
async def read_items():
return {"message": "Hello World"}在这个例子中,common_parameters 函数被用作依赖项,并通过 dependencies 参数注入到 /items/ 路径操作中。
3. 依赖项的执行顺序
当请求到达路径操作时,FastAPI 会首先执行 dependencies 参数中指定的所有依赖项。这些依赖项会按照它们在列表中出现的顺序依次执行。每个依赖项可以返回一些数据,这些数据可以在路径操作函数中使用。
4. 依赖项的返回值
依赖项可以返回任何类型的数据,这些数据可以在路径操作函数中使用。例如,common_parameters 函数返回一个包含查询参数的字典,这个字典可以在路径操作函数中访问。
@app.get("/items/", dependencies=[Depends(common_parameters)])
async def read_items(commons: dict = Depends(common_parameters)):
return commons在这个例子中,commons 参数会接收 common_parameters 函数返回的字典。
5. 依赖项的错误处理
如果依赖项中发生错误(例如抛出 HTTPException),FastAPI 会立即停止执行后续的依赖项和路径操作函数,并返回相应的错误响应。
def check_admin_user(username: str = Depends(get_current_user)):
if username != "admin":
raise HTTPException(status_code=403, detail="Not authorized")
return username
@app.get("/admin/", dependencies=[Depends(check_admin_user)])
async def admin_panel():
return {"message": "Welcome to the admin panel"}在这个例子中,如果当前用户不是 admin,check_admin_user 会抛出一个 HTTPException,FastAPI 会返回一个 403 错误响应,并且不会执行 admin_panel 函数。