簡體   English   中英

使用 FastAPI 后端接收 JSON

[英]Reciving JSON with FastAPI-backend

從我的前端發送 JSON 到我的后端並在那里讀取它時我遇到了一個小問題。 首先是簡單的部分,在我的index.html中,我閱讀了一些字段中寫的內容並將其傳遞給var inputs

 <script type="text/javascript"> function get_inputs() { var inputs = { T_0: document.getElementById("a").value, E_A: document.getElementById("b").value, } backend_test(inputs) console.log("input:" + JSON.stringify(inputs)) return inputs } </script>

"console.log("input:" + JSON.stringify(inputs))" 輸出到控制台:

輸入:{“T_0”:“3”,“E_A”:“5”}

這調用了 function backend_test,它應該接受我所做的輸入並通過 GET 請求將其作為 JSON 發送到我的 FastAPI:

 function backend_test(inputs) { var inputs = inputs console.log('frontend_func inputs out: ' + JSON.stringify(inputs)) $(document).ready(function() //supposed to wait for the functions to be fully loaded { $.ajax({ type: 'GET', contentType: 'application/json', data: JSON.stringify(inputs), dataType: "json", url:"fastapi/compute", success: function (result) { console.log(result) console.log("should work") }, error: function (error) { console.log(error) console.log("error, but where?") } }); }); return("yay") }

現在,在我的后端,我想以某種方式使用這些信息進行進一步計算:

from fastapi import Request, FastAPI
from pydantic import BaseModel
from .self_ignition import test_function
from typing import List

class Liste(BaseModel):
    T_0: int
    E_A: int

@app.get("/compute")
def calculate(liste: Liste):

    
    return {"backend output:" + liste}

按原樣發送請求會在我的前端控制台中傳遞一個“錯誤 422 無法處理的實體”,我得到“錯誤,但是在哪里?” 在我的“backend_test”function 中定義的消息。與后端的連接在那里,調用 /compute 並且在 calculate() 中沒有任何輸入將給我在 function backend_test(inputs) 中定義的成功 output:“應該工作”。 我無法直接查看后端代碼中的錯誤,因為公司 GitLab 框架中的所有內容都已設置,並且只有通過提交更改並啟動更新的網頁才能進行測試。

使用“基本模型”是我在文檔中閱讀它之后的最后一次嘗試,那個人在做一個類似的項目,但是使用不同的 API 只需要寫“def calculate(body)”並且有他的信息,但這不是'似乎在這個 API 中不起作用

請注意,這些只是使連接正常工作的代碼的一部分。 我真正需要的是了解 FastAPI 如何處理 JSON 的接收,因為文檔並沒有真正幫助我讓它工作。

在此先感謝,我在這個小問題上坐了 2 天,並不斷返回相同的幫助頁面,但無法使其正常工作。

解決方案:

將 Number() 添加到這部分,因為我稍后將它們稱為 int 而不是 str:

T_0 : Number(document.getElementById("a").value),
E_A : Number(document.getElementById("b").value),

在此處將類型更改為 POST:

$.ajax({
            type: 'POST',

和這里:

@app.post("/compute")

並且不要嘗試返回列表,而是返回一個將此列表的元素作為 str 的變量:

x=str(liste.T_0)

return {"backend output:"+x}

您應該將值轉換為 integer。

您的 model 需要整數。

class Liste(BaseModel):
    T_0: int
    E_A: int

這意味着你應該像這樣發送

{"T_0": int,"E_A": int}

但是在您當前的情況下,您發送的是string而不是int

使用NumberparseInt將其轉換為 int 然后它應該可以工作。

將您的請求方法更改為發布。

type: 'POST'

您還可以更改在服務器端發布的方法。

@app.post("/compute")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM