【问题标题】:Not able to pass json object to python server program无法将 json 对象传递给 python 服务器程序
【发布时间】:2016-02-15 05:34:02
【问题描述】:

我有一个关于 python flask 和 jquery 的应用程序。每当我尝试对某些事件调用日志记录机制时,我都会遇到以下问题。我在stackoverflow上没有找到可以解决这个问题的答案

POST http://localhost:5000/uploadLog/[object%20Object] 500 (INTERNAL SERVER ERROR)

在 frontend.js 文件中:

    var eventObj = { 
                               'eventType': 'Type1',
                               'eventDesc': event.target.href
            };
$.post('/uploadLog/'+eventObj, function(response){
            alert("successfully logged");
        })

在controller.py中:

@app.route('/uploadLog/<eventObj>', methods=['POST'])
def uploadLog(eventObj):
    loggerProg.updateLog(eventLogObj)
    return jsonify({'status':'success'})

在 loggerProg.py 中:

def updateLog(eventObj):
    parsed_obj = json.load(eventObj)

我尝试将 eventObj 写入文件,但文件中出现“[object Object]”。

【问题讨论】:

  • 不能在 URL 中传递 Json 对象,将其作为数据发送。

标签: jquery python json rest logging


【解决方案1】:

您需要 a) 在将 JavaScript 对象 POST 到服务器之前对其进行序列化,b) 将请求的 Content-Type 标头设置为 application/json,如下所示:

$.ajax({
    url: "/uploadLog",
    type: "POST",
    data: JSON.stringify(eventObj),
    contentType: "application/json",
    success: function() {
        alert("Success!");
    }
});

然后在服务器上,为了方便,使用Flask的get_json()函数解析请求体:

@app.route('/uploadLog', methods=['POST'])
def uploadLog():
    parsed_obj = request.get_json()

【讨论】:

  • 您可以运行 fiddler 跟踪并确保 POST 转到正确的 url 吗?它应该是'/uploadLog'
  • 它不起作用。收到此错误 - 500(内部服务器错误)
  • 是的。它会转到正确的网址 - localhost:5000/uploadLog 。我正在 chrome 开发人员工具中检查这一点。我什至尝试使用 json.loads() 而不是 json.load()
  • 请看我更新的答案。我在请求上设置“内容类型”,并在服务器上使用便捷方法 request.get_json()。
  • 太棒了。它就像魅力一样!谢谢。这是非常有用的方法。早些时候, request.body 没有工作。知道为什么它不起作用吗?一旦您分享此信息,我会立即标记您的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多