Python Flask-request.json返回None类型而不是json字典 [英] Python Flask - request.json returns None Type instead of json dictionary
问题描述
我正在编写一个非常简单的演示Web应用程序,并且似乎无法使用 ajax js 传递给 python >.
I'm writing a very simple demo webapp, and I can't seem to pass a json object from js to python using ajax.
我尝试了很多类似问题的建议,例如使用.get_json()
而不是.json
,不使用javascript在不使用JSON.stringify
的情况下传递对象等.
I've tried a number of suggestions from people on so with similar problems, such as using .get_json()
instead of .json
, passing the object without using JSON.stringify
in the javascript, etc.
知道我在这里遗失了什么吗?
Any idea what piece I'm missing here?
JavaScript
var run_method = function(){
var data1 = {"word":"hello"}
console.log("Before " + data1);
$.ajax({
url : "/examplemethod",
type : "POST",
data : data1//JSON.stringify(data1)
})
.done(function(data){
var data = JSON.parse(data);
console.log(data);
});
}
Python
@app.route("/examplemethod", methods=['POST', 'GET'])
def example_method():
global data
if request.method == 'POST':
print request
data = request.json
print "data", data
return "after "+ data["word"]
我尝试过的每个变化都会给出 500错误,并且
Every variation I have tried of this gives a 500 Error, and
TypeError:"NoneType"对象没有属性" getitem "
很明显,这是因为数据应该是dictionary/json
,而不是None
.但是,如何获取它作为字典返回呢?
Obviously, that is because data is supposed to be an dictionary/json
, not None
. But how to I get it to return as a dictionary?
推荐答案
因为您没有向flask应用发送JSON(请参见此).您当前的代码会产生一个标准的urlencoded表单发布.反过来导致在request.form
Because you are not sending JSON, to the flask app (see this and this). Your current code results in a standard urlencoded form post. Which in turn results in an entry being populated in request.form
request.form.get('word')
根据上述问题与解答中的指南切换到json帖子,以通过request.json访问数据.
Switch to a json post as per the guidelines in the above Q&As to access the data through request.json.
这篇关于Python Flask-request.json返回None类型而不是json字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!