我正在嘗試使用 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
有沒有人知道如何在端點中獲取更多資料?謝謝!
uj5u.com熱心網友回復:
您可以宣告一個型別為List并顯式使用的查詢引數Query,如this和this answer中所示,以及檔案中所述。這樣,您可以接收查詢引數的多個值,例如,
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 引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/468805.html
