简体   繁体   English

使用 FastAPI 后端接收 JSON

[英]Reciving JSON with FastAPI-backend

I have a little problem with sending JSON from my frontend to my backend and reading it there.从我的前端发送 JSON 到我的后端并在那里读取它时我遇到了一个小问题。 At first the easy part, in my index.html I read what's written in some fields and pass it to var inputs首先是简单的部分,在我的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))" outputs to console: "console.log("input:" + JSON.stringify(inputs))" 输出到控制台:

input:{"T_0":"3","E_A":"5"}输入:{“T_0”:“3”,“E_A”:“5”}

this calls the function backend_test which is supposed to take the input I made and send it as JSON via a GET request to my FastAPI:这调用了 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") }

Now, at my backend, I somehow want to use the information for further calculations:现在,在我的后端,我想以某种方式使用这些信息进行进一步计算:

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}

Sending the request as it is delivers an "Error 422 Unprocessable Entity" in my frontend console and i get the "error, but where?"按原样发送请求会在我的前端控制台中传递一个“错误 422 无法处理的实体”,我得到“错误,但是在哪里?” message defined in my "backend_test" function. A connection to the backend is there, calling /compute and not having any inputs in calculate() will give me the in function backend_test(inputs) defined success output: "should work".在我的“backend_test”function 中定义的消息。与后端的连接在那里,调用 /compute 并且在 calculate() 中没有任何输入将给我在 function backend_test(inputs) 中定义的成功 output:“应该工作”。 I cant look into errors in the backend code directly because everything is set_up in a company GitLab Framework and testing is only possible by commiting changes and starting the updated Webpage.我无法直接查看后端代码中的错误,因为公司 GitLab 框架中的所有内容都已设置,并且只有通过提交更改并启动更新的网页才能进行测试。

Using "Base Model" was my last try after reading about it in the documentation, the guy working on a similar project, but with a different API simply had to write "def calculate (body)" and there was his information but this doesn't seem to work in this API使用“基本模型”是我在文档中阅读它之后的最后一次尝试,那个人在做一个类似的项目,但是使用不同的 API 只需要写“def calculate(body)”并且有他的信息,但这不是'似乎在这个 API 中不起作用

Note that these are only parts of the code for making the connection work.请注意,这些只是使连接正常工作的代码的一部分。 What I really need is to know how FastAPI handels the receiving of JSON because the documentation didn't really help me make it work.我真正需要的是了解 FastAPI 如何处理 JSON 的接收,因为文档并没有真正帮助我让它工作。

Thanks in advance, I'm sitting on this little problem for 2 days and keep coming back to the same help-pages but cant make it work.在此先感谢,我在这个小问题上坐了 2 天,并不断返回相同的帮助页面,但无法使其正常工作。

Solution:解决方案:

add Number() to this part because i later adress them as int not str:将 Number() 添加到这部分,因为我稍后将它们称为 int 而不是 str:

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

change type to POST here:在此处将类型更改为 POST:

$.ajax({
            type: 'POST',

and here:和这里:

@app.post("/compute")

and don´t try to return the list but a variable that takes elements of this list as str:并且不要尝试返回列表,而是返回一个将此列表的元素作为 str 的变量:

x=str(liste.T_0)

return {"backend output:"+x}

You should convert values to integer.您应该将值转换为 integer。

Your model expects integers.您的 model 需要整数。

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

Which means you should send like this这意味着你应该像这样发送

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

But in your current situation, you are sending string instead of int .但是在您当前的情况下,您发送的是string而不是int

Convert it to int using Number or parseInt then it should work.使用NumberparseInt将其转换为 int 然后它应该可以工作。

Change your request method to post.将您的请求方法更改为发布。

type: 'POST'

Also your change your method to post on your server side.您还可以更改在服务器端发布的方法。

@app.post("/compute")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM