【问题标题】:FastAPI: can I use Depends() for parameters in a POST, too?FastAPI:我也可以将 Depends() 用于 POST 中的参数吗?
【发布时间】:2021-03-22 00:52:32
【问题描述】:

概述

我创建了一个基于类的依赖项,类似于惊人的 FastAPI tutorial 中的内容。

问题

它可以工作,除了依赖项中的参数(Depends() 部分)作为查询参数传递,这意味着它们是 URI/URL 的一部分。我使用基于类的依赖项来简化对 Azure Datalake 的访问,因此 Depends 中的参数至少有些保密。所以我希望他们出现在 POST 部分。

问题

有没有办法使用Depends(),但通过 POST 有效负载而不是 URL 路径传递类初始化参数?

详情

举个例子:

依赖类(只是初始化,捕获依赖参数):

class DatalakeConnection(object):
    """Using FastAPI's `Depends` Dependency Injection, this class can have all
    elements needed to connect to a data lake."""

    def __init__(
        self,
        dir: str = my_typical_folder,
        container: str = storage_container.value,
    ):
        service_client = DataLakeServiceClient(
            account_url=storage_uri,
            credential=storage_credential,
        )
        self.file_system_client = service_client.get_file_system_client(
            file_system=container
        )
        self.directory_client = self.file_system_client.get_directory_client(dir)
        self.file_client = None

FastAPI 路径函数:

@app.post("/datalake")  # I have no response model yet, but will add one
def predictions_from_datalake(
    query: schemas.Query, conn: DatalakeConnection = Depends()
):
    core_df = conn.read_excel(query.file_of_interest) # I create a DataFrame from reading Excel files

总结

正如我所说,这可行,但是初始化类所需的 dircontainer 被强制输入 URL 查询参数,但我希望它们成为 POST 请求正文中的键值对:

【问题讨论】:

标签: python post dependency-injection fastapi depends


【解决方案1】:

您可以像路径操作体参数一样声明它们。更多信息在这里Singular values in body

class DatalakeConnection(object):
    """Using FastAPI's `Depends` Dependency Injection, this class can have all
    elements needed to connect to a data lake."""

    def __init__(
            self,
            dir: str = Body("dir_default"),
            container: str = Body("container_default"),
    ):
        pass

请求正文示例:

{
  "dir": "string",
  "container": "string"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-21
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    相关资源
    最近更新 更多