我正在尝试使用 FastAPI + MongoDB 创建一个 API,它可以从请求返回多个值。 MongoDB 充满了数据,使用 mongoengine,我可以在向特定端点发送请求时查阅一个或所有数据。 我现在想做的是从端点接收一个或多个数据,例如:
在咨询端点时
http://127.0.0.1:8000/rice
我收到一个 JSON 响应,其中包含 MongoDB 上该项目的所有数据。但问题是,我需要让这个端点咨询来自 MongoDB 的一个或多个数据,并返回用户发送到端点的尽可能多的数据,例如:http://127.0.0.1:8000/rice&pasta&bean
并返回 JSON 及其在 MongoDB 中的信息关于 rice
、pasta
和 bean
。
在代码中我有一个 main.py ,其路由如下:
@app.get('/{description}', status_code=200)
def get_description(description):
return JSONResponse(TabelaService().get_description(description))
此函数调用另一个函数,该函数又调用另一个函数,该函数使用
queryset
来查询 MongoDB 中的数据并将其序列化:
def get_description(self, description):
try:
description = TabelaNutricional.get_by_description(description)
return self.serialize(description)
except:
raise DescriptionNotFound
下面是从 MongoDB 获取数据的函数:
@queryset_manager
def get_by_description(doc_cls, queryset, description):
nutriente = queryset(description=str(description)).get()
return nutriente
有人知道如何在端点中获取更多数据吗? 谢谢!
您可以声明类型为
List
的查询参数并显式使用 Query
,如 this 和 this 答案中所示,以及 文档 中所述。通过这种方式,您可以接收查询参数的多个值,例如,
http://127.0.0.1:8000/?item=rice&item=pasta&item=bean
在服务器端,您可以循环遍历项目列表并为列表中的每个项目调用函数,并创建一个字典并将结果发送回客户端。例如:
@app.get('/', status_code=200)
def get_description(item: List[str] = Query(...)):
data = {}
for i in item:
d = TabelaService().get_description(i)
data[i] = d
return JSONResponse(data)
如果您仍然想使用 Path 参数,您可以使用下面的参数并按问题中所示的方式调用它,即
http://127.0.0.1:8000/rice&pasta&bean
:
@app.get('/{items}', status_code=200)
def get_description(items: str):
items = items.split('&')
data = {}
for i in items:
d = TabelaService().get_description(i)
data[i] = d
return JSONResponse(data)
注意: 如果您使用上述内容(带有路径参数),则http://127.0.0.1:8000/docs 处的 OpenAPI 文档(Swagger UI)将不会加载。这是因为当访问该 URL 时,会调用上面的端点,并将
docs
作为 items
路径参数的值。因此,您可以在该端点上添加额外的路径,例如 @app.get('/api/{items}'
并使用 http://127.0.0.1:8000/api/rice&pasta&bean
等调用该路径(从而允许 /docs
成功加载),或者使用带有 Query 参数的第一种方法.