简体   繁体   English

如何在 python 中使用 flask 从 post 请求中检索数据

[英]How to retrieve data from a post request using flask in python

I am working on a rest api using flask. Currently the code for the client is as follows:我正在使用 flask 处理 rest api。目前客户端的代码如下:

new_data = {'msg': message,
        'rec':rec_id,
        'snd':my_id}
        requests.post("http://localhost:33/api/resources/messages/all", json = new_data)

I did print out new_data and it does print fine it does print out fine我确实打印出 new_data 并且它确实打印得很好它确实打印出很好

{'msg': 'This is a message', 'rec': 1, 'snd': 0} {'msg': '这是一条消息', 'rec': 1, 'snd': 0}

and the code in the rest api is: rest api 中的代码是:

@app.route('/api/resources/messages/all', methods=['GET', 'POST'])
def api_messages():
    if request.method == "GET":
        return jsonify(messages)
    if request.method == "POST":
        sentmsg = request.json
        print (sentmsg)

changing改变

sentmsg = request.json sentmsg = request.json

to

sentmsg = request.get_json()发送消息 = request.get_json()

did not change anything as it still results in the same error.没有改变任何东西,因为它仍然导致相同的错误。 Specifying the content type also did not result in any changes to the result.指定内容类型也不会导致结果发生任何变化。

However this code results in the error when attempting to post it.但是,此代码在尝试发布时会导致错误。

TypeError: Object of type type is not JSON serializable类型错误:Object 类型类型不是 JSON 可序列化

How can I change this code in order to make it so the json is passed to the rest api and can be printed out in json form.我怎样才能更改此代码,以便将 json 传递给 rest api 并以 json 形式打印出来。

The issue did not originate from the code shown in the initial post.该问题并非源自初始帖子中显示的代码。 The error originates at the start of the code where I declared two of the variables used here:错误源自代码的开头,我在其中声明了此处使用的两个变量:

my_id = int
rec_id = int

Since these 2 variables did not have a value it was causing issues when it was called.由于这 2 个变量没有值,因此在调用时会导致问题。 As such it resulted in the error message "TypeError: Object of type type is not JSON serializable" (This error message itself gives a good indicator that one or more of the variables used were likely blank and held no value, thus making it unable to specify the data type in the message).因此,它导致了错误消息“TypeError: Object of type type is not JSON serializable”(此错误消息本身很好地表明所使用的一个或多个变量可能为空且没有值,因此使其无法指定消息中的数据类型)。

As such giving these variables an actual value caused the program to work fine.因此,给这些变量一个实际值会使程序运行良好。 A second error that only become obvious after was that request.get_json needed to have brackets after get_json , making it request.get_json() .之后才变得明显的第二个错误是request.get_json需要在get_json之后有括号,使其成为request.get_json()

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

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