【问题标题】:Parse JSON object from a POST request body in Django/python based server从基于 Django/python 的服务器中的 POST 请求正文中解析 JSON 对象
【发布时间】:2015-10-04 06:23:23
【问题描述】:

我正在使用以下函数将 JSON 格式的数据发送到基于 Django 的服务器,该服务器存储为数据库中的用户生成的用户密钥。当我尝试在 Django 上使用 python 访问服务器端的request.body 时,它被打印为字符串[object Object]。如何处理从服务器端 request.body 解析 json 的这一部分。 函数完成密钥生成(数据) { var key_data = { 'user_id':user_id, “钥匙”:数据 } 删除数据['action']; console.log("发送 UBE 密钥给用户"); console.log(key_data);

    var oReq = new XMLHttpRequest();
    oReq.open("POST",CLOUD_SERVER+'add_ube_keys',true);
    oReq.responseType = "json";
    oReq.setRequestHeader("Content-type", "application/json");
    oReq.onload = function(oEvent){
        console.log(oReq.response.success);
    };
    oReq.send(key_data);
}

供参考服务器端代码:

@csrf_exempt
def add_ube_keys(request):
    data = request.POST
    print data.get('user_id')
    return_data = {
        'success':True
    }
    rdata = json.dumps(return_data)
    return HttpResponse(rdata, content_type='application/json')

与可能重复的问题不同,我在print request.POST 上得到Querydict 对象返回<QueryDict: {}>。为什么是空的?

【问题讨论】:

标签: python json django xmlhttprequest


【解决方案1】:

我仍然不知道我在上述问题中的方法有什么问题,但我分三步解决了这个问题:

  1. 在发送 XMLHttpRequest 之前,我在 javascript 中添加了JSON.stringify(key_data)。

  2. 将application/json 更改为application/x-www-form-urlencoded。

  3. 现在python端把数据当作普通字符串,所以我用json.loads(request.body)从字符串化的数据中提取json对象。

以上两个步骤取自之前发布的问题: How to receive POST data in python when using XMLHttpRequest()

【讨论】:

    【解决方案2】:

    request.POST 现在只包含表单数据。您必须从 request.body 解析出 JSON。

    https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.POST

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-28
      • 2011-02-04
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多