javascript 当通过 post 请求发送有效的 json 数据时,Flask request.get_json() 返回 None
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49010415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask request.get_json() returning None when valid json data sent via post request
提问by 0_insomniac_0
Building an app using flask. The app uses a table structure to display data. Part of its functionality is collecting the data from user specified table rows. To do this I have placed a button on each row that executes some js. The js collects the information from the row, uses JSON.stringify() to convert to json object and the issues the post request to the relevant flask url.
使用 Flask 构建应用程序。该应用程序使用表结构来显示数据。它的部分功能是从用户指定的表行中收集数据。为此,我在执行一些 js 的每一行上放置了一个按钮。js 从行中收集信息,使用 JSON.stringify() 转换为 json 对象,并将 post 请求发送到相关的flask url。
Logging the value of the jsonified object to the browser console from js file shows it is correctly formed. The post request contacts the correct route however the request.get_json() function returns a value of None in the method of that route.
将 jsonified 对象的值从 js 文件记录到浏览器控制台表明它的格式正确。post 请求联系正确的路由,但是 request.get_json() 函数在该路由的方法中返回 None 值。
I have set up a seperate route in flask for testing. Here is the relevant code
我在烧瓶中设置了单独的路线进行测试。这是相关的代码
from javascript
来自 javascript
function do_some_work(e) {
var row_data = get_table_row_data(e);
row_data = JSON.stringify(row_data);
console.log(row_data);
$.post("test", row_data);
}
get_table_row_data() simply returns an object with key:value pairs. The log shows the data is correctly formatted json.
get_table_row_data() 只是返回一个带有键值对的对象。日志显示数据格式正确 json。
And here is the python code
这是python代码
#TODO
@application.route('/test', methods=['GET', 'POST'])
def test():
data = request.get_json()
print("data is "+format(data))
return redirect(url_for('index'))
Here data is coming up as None
这里的数据显示为 None
any help much appreciated
非常感谢任何帮助
回答by Marvin
It's request.jsonit will return a dictionary of the JSON data. To get a value you use request.json.get('value_name'). So your route will be like this
它request.json会返回一个 JSON 数据字典。要获得您使用的值request.json.get('value_name')。所以你的路线会是这样
#TODO
@application.route('/test', methods=['GET', 'POST'])
def test():
data = request.json
print("data is " + format(data))
return redirect(url_for('index'))

