【发布时间】: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
总结
正如我所说,这可行,但是初始化类所需的 dir 和 container 被强制输入 URL 查询参数,但我希望它们成为 POST 请求正文中的键值对:
【问题讨论】:
-
您可以在函数中访问
Request对象并在那里做一些事情,但我不知道类是否可以。 fastapi.tiangolo.com/advanced/using-request-directly/…
标签: python post dependency-injection fastapi depends