【问题标题】:How to post data structure like json to flask?如何将json之类的数据结构发布到flask?
【发布时间】:2013-02-11 09:43:55
【问题描述】:

我有这样的数据结构:

我正在尝试通过 $.ajax 将其发送到服务器:

$.ajax({
    type: 'POST',
    data: post_obj, //this is my json data
    dataType: 'json',
    url: '',
    success: function(e){
       console.log(e);
    }
});

我想通过烧瓶将它放入服务器:title = request.form['title'] 工作正常!

但是我如何获得content

request.form.getlist('content') 不起作用。

这是firebug中的post数据:

非常感谢:D

【问题讨论】:

  • content = request.form['content'] 怎么样? :)
  • @favoretti 无法工作:BadValueException: Bad value for field of type "content". Reason: "Value is not an instance of <type 'basestring'> (got: list)"
  • 好的,request.form.getlist('content') 返回什么?关于“不起作用”的更多细节可能会有所帮助。不幸的是,这里没有手边的烧瓶来测试。
  • 它返回与 request.form['content'] 相同的错误。 ps:在萤火虫中发布数据可能会有所帮助。

标签: python json post flask


【解决方案1】:

您正在发送编码为查询字符串而不是 JSON 的数据。 Flask 能够处理 JSON 编码的数据,所以这样发送更有意义。以下是您需要在客户端执行的操作:

$.ajax({
    type: 'POST',
    // Provide correct Content-Type, so that Flask will know how to process it.
    contentType: 'application/json',
    // Encode your data as JSON.
    data: JSON.stringify(post_obj),
    // This is the type of data you're expecting back from the server.
    dataType: 'json',
    url: '/some/url',
    success: function (e) {
        console.log(e);
    }
});

通过request.json(已解码)访问服务器端数据:

content = request.json['content']

【讨论】:

    【解决方案2】:

    如果您检查 jQuery 提交的 POST,您很可能会看到 content 实际上是作为 content[] 传递的。要从 Flask 的 request 对象访问它,您需要使用 request.form.getlist('content[]')

    如果您希望将其作为content 传递,您可以将traditional: true 添加到您的$.ajax() 调用中。

    有关此内容的更多详细信息,请参阅http://api.jquery.com/jQuery.ajax/ 的“数据”和“传统”部分。

    【讨论】:

    • 当我将 traditional: true 设置为 $.ajax 时。我在服务器中收到了类似[object Object] 的字符串...但这不是我想要的:(
    • 不同的服务器端技术处理不同。您可能想查看 Audrius 提供的有关 JSON 的答案。
    猜你喜欢
    • 2017-06-10
    • 2013-11-03
    • 2012-06-21
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    相关资源
    最近更新 更多