是否可以将 Path 参数传递到 FastAPI 依赖函数中?

Phi*_*ing 20 python fastapi

无论如何,FastAPI“依赖项”是否可以解释路径参数?

我有很多形式的函数:

@app.post("/item/{item_id}/process", response_class=ProcessResponse)
async def process_item(item_id: UUID, session: UserSession = Depends(security.user_session)) -> ProcessResponse:
    item = await get_item(client_id=session.client_id, item_id=item_id)
    await item.process()
Run Code Online (Sandbox Code Playgroud)

一次又一次,我需要传入[多个]参数来获取所需的项目,然后再对其进行操作。这是非常重复的并且使得代码非常冗长。我真正想做的是将itemin 作为参数传递给该方法。

理想情况下,我想建立get_item一个依赖项或以某种方式将其嵌入到路由器中。这将大大减少重复的逻辑和过于冗长的函数参数。问题在于客户端在路径中传递了一些关键参数。

是否可以将 Path 参数传递到依赖项中,或者可能在路由器中执行依赖项并传递结果?

Dar*_*ren 33

FastAPI 依赖函数可以采用普通端点函数可以采用的任何参数。

因此,在普通端点中,您可以定义一个路径参数,如下所示:

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id):
    return {"item_id": item_id}
Run Code Online (Sandbox Code Playgroud)

现在,如果您想在依赖项中使用该参数,您可以简单地执行以下操作:

from fastapi import Depends, FastAPI

app = FastAPI()

async def my_dependency_function(item_id: int):
    return {"item_id": item_id}


@app.get("/items/{item_id}")
async def read_item(item_id: int, my_dependency: dict = Depends(my_dependency_function)):
    return my_dependency
Run Code Online (Sandbox Code Playgroud)

如果参数存在,则它们将简单地传递到依赖函数。您还可以在依赖函数中使用诸如Path和 之类的东西Query来定义它们的来源。

它只会分析请求对象来提取这些值。

Path以下是使用FastAPI 中的函数的示例:

from fastapi import Depends, FastAPI, Path

app = FastAPI()

async def my_dependency_function(item_id: int = Path(...)):
    return {"item_id": item_id}


@app.get("/items/{item_id}")
async def read_item(my_dependency: dict = Depends(my_dependency_function)):
    return my_dependency
Run Code Online (Sandbox Code Playgroud)

至于您关心将其实现为路由器中的依赖项,您可以在创建路由器时执行以下操作:

items_router = APIRouter(
    prefix="/items",
    tags=["items"],
    dependencies=[Depends(my_dependency_function)],
)
Run Code Online (Sandbox Code Playgroud)

或者,您可以在运行include_router应用程序时执行此操作,例如:

app.include_router(
    items_router,
    prefix="/items",
    dependencies=[Depends(my_dependency_function)],
)
Run Code Online (Sandbox Code Playgroud)

有关依赖项的更多信息和更多类似示例,请参阅https://fastapi.tiangolo.com/tutorial/dependency/

  • 如果“my_dependency_function”需要其他参数(例如数据库服务)怎么办? (2认同)
  • @maudev 理想情况下,您将有一个创建数据库连接的依赖函数,此时只需从任何依赖项需要的地方调用该函数即可。这就是我要做的。 (2认同)