在某些情况下,您实际上不需要在路径操作函数内返回依赖项的返回值。
或依赖项不返回值。但是您仍然需要执行/解决它。
在这种情况下,您可以将依赖项list添加到路径操作修饰符,而不是使用Depends声明路径操作函数参数。
向路径操作装饰器添加依赖项
路径操作装饰器接收可选的参数依赖项。
它应该是Depends()的列表:
from fastapi import Depends, FastAPI, Header, HTTPExceptionapp = FastAPI()async def verify_token(x_token: str = Header(...)):if x_token != "fake-super-secret-token":raise HTTPException(status_code=400, detail="X-Token header invalid")async def verify_key(x_key: str = Header(...)):if x_key != "fake-super-secret-key":raise HTTPException(status_code=400, detail="X-Key header invalid")return x_key@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])async def read_items():return [{"item": "Foo"}, {"item": "Bar"}]
这些依赖关系将以与普通依赖关系相同的方式执行/解决。但是它们的值(如果它们返回任何值)将不会传递到您的path操作函数。
:::tips
一些编辑器检查未使用的功能参数,并将其显示为错误。
在路径操作修饰符中使用这些dependencies,可以确保它们在避免编辑器/工具错误的情况下得以执行。
对于那些在代码中看到未使用的参数并且认为不必要的新开发人员,这也可能有助于避免混淆。
:::
依赖项错误和返回值
依赖需求
他们可以声明请求要求(例如标头)或其他子依赖项:
from fastapi import Depends, FastAPI, Header, HTTPExceptionapp = FastAPI()async def verify_token(x_token: str = Header(...)):if x_token != "fake-super-secret-token":raise HTTPException(status_code=400, detail="X-Token header invalid")async def verify_key(x_key: str = Header(...)):if x_key != "fake-super-secret-key":raise HTTPException(status_code=400, detail="X-Key header invalid")return x_key@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])async def read_items():return [{"item": "Foo"}, {"item": "Bar"}]
抛出异常
这些依赖项会引发异常,与普通依赖项相同:
from fastapi import Depends, FastAPI, Header, HTTPExceptionapp = FastAPI()async def verify_token(x_token: str = Header(...)):if x_token != "fake-super-secret-token":raise HTTPException(status_code=400, detail="X-Token header invalid")async def verify_key(x_key: str = Header(...)):if x_key != "fake-super-secret-key":raise HTTPException(status_code=400, detail="X-Key header invalid")return x_key@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])async def read_items():return [{"item": "Foo"}, {"item": "Bar"}]
返回值
而且它们可以返回值或不返回值,这些值将不会被使用。
因此,您可以重复使用已经在其他地方使用的普通依赖项(返回一个值),即使不使用该值,该依赖项也将被执行:
from fastapi import Depends, FastAPI, Header, HTTPExceptionapp = FastAPI()async def verify_token(x_token: str = Header(...)):if x_token != "fake-super-secret-token":raise HTTPException(status_code=400, detail="X-Token header invalid")async def verify_key(x_key: str = Header(...)):if x_key != "fake-super-secret-key":raise HTTPException(status_code=400, detail="X-Key header invalid")return x_key@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])async def read_items():return [{"item": "Foo"}, {"item": "Bar"}]
一组路径操作的依存关系
稍后,当阅读有关如何构造可能包含多个文件的更大应用程序(更大应用程序-多个文件)时,您将学习如何为一组路径操作声明单个依赖项参数。
