FastAPI依赖注入系统系列(四) 路径操作装饰器中的依赖项

一、路径操作装饰器中添加依赖项

在某些场景中你可能不需要在路径操作函数中去接收依赖项的返回值,或者这个依赖项根本没有返回值。但是你仍然需要去执行这些依赖项。

对于这些场景,不要通过在路径操作函数中去声明Depends参数,你可以在路径操作装饰器中去添加一个dependencies的列表。

比如:

from fastapi import Depends, FastAPI, Header, HTTPException

app = 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():
    items = [
        {"name": "apple", "price": "1.12"},
        {"name": "pear", "price": "3.14"}
    ]
    return items

上面的verify_token、verify_key依赖项和正常的依赖项一样的执行,但是它们的的返回值(如果它们存在return返回值)不会传递给路径操作函数。

二、依赖项注意事项

虽然上述的依赖项时放在dependencies的列表中,但是它们可以像正常依赖项一样:

  • 声明请求的参数、请求头(Header)等
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
  • 这些依赖项与正常依赖项一样可以抛出异常,这些异常是会在前台返回的
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
  • 尽管依赖有返回值,但是不会被使用
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
作者:iveBoy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/shenjianping/p/14862797.html