【问题标题】:Python Flask - request.json returns None Type instead of json dictionaryPython Flask - request.json 返回 None 类型而不是 json 字典
【发布时间】:2017-05-25 05:04:47
【问题描述】:

我正在编写一个非常简单的演示 webapp,我似乎无法使用 ajax将 json 对象从 js 传递到 python >.

我尝试了很多人提出的一些类似问题的建议,例如使用.get_json()而不是.json,在javascript中传递对象而不使用JSON.stringify等。

知道我在这里缺少什么吗?

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 错误,并且

TypeError: 'NoneType' 对象没有属性 'getitem'

显然,这是因为数据应该是dictionary/json,而不是None。但是如何让它作为字典返回呢?

【问题讨论】:

  • 你试过我的答案了吗?
  • 是的,我做到了 - 谢谢。但是,它似乎没有解决任何问题。
  • 你的回答没有解决我的问题,所以我没有采纳。我最终弄清楚了,但没有使用您在此处描述的内容。抱歉,我没有时间挖掘该代码并进一步详细说明。
  • 如果你解决了你的问题,你应该发布你的解决方案。

标签: python json flask


【解决方案1】:

因为您没有将 JSON 发送到烧瓶应用程序(请参阅 thisthis)。您当前的代码会生成一个标准的 urlencoded 表单帖子。这反过来会导致在request.form中填充一个条目

 request.form.get('word')

按照上述问答中的指南切换到 json 帖子,以通过 request.json 访问数据。

【讨论】:

    【解决方案2】:

    如果你得到None,数据可能不会流向json,所以你应该对数据进行json化。它将以form 的形式出现。

    from flask import jsonify
    
    @app.route("/examplemethod", methods=['POST'])
    def example_method():
        data = jsonify(request.form).json
        print(data) #will be in the form a json dict
        return data['foo-key'] #can retrieve specific items with their key-pairs
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 2020-02-15
      • 2015-07-03
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多