1

概述

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

问题

它可以工作,只是依赖项(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 请求正文中的键值对:

Swagger UI 的图像将 dir 显示为查询参数,而不是 POST 正文的一部分

4

1 回答 1

2

您可以像路径操作体参数一样声明它们。此处的更多信息主体中的奇异值

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"
}
于 2020-12-11T06:56:14.797 回答