Python POST请求找不到数据属性 [英] Python POST request can't find data attribute

查看:493
本文介绍了Python POST请求找不到数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Python向我的Django REST API写入POST请求,但似乎无法在请求的数据部分中找到属性.这是处理请求的函数:

I'm trying to write a POST request to my Django REST API in Python, but it can't seem to find an attribute in the data section of the request. Here's the function that handles the request:

 def post(self, request, id, format=None):
    obj = self.get_object_or_404(id)

    operation = request.POST.get('operation', None)
    if operation == None:
        print "Operation was none, uh oh."
        return Response()
    else:
        print "It worked!"
        return Response()

现在这是jquery中的POST ajax调用.这个作品. (打印它起作用了!")

Now here's a POST ajax call in jquery. This one works. (Prints "It worked!")

$.ajax({
  method: 'POST',
  beforeSend: function(xhr) { xhr.setRequestHeader('Authorization', 'Token ' + token)},
  url: url,
  data: {
    'operation':-1,
  },
  success: callback,
  error: function (jqXHR, textStatus, errorThrown) {
    console.log(textStatus);
    console.log(errorThrown);
  }
});

现在这是Python中的POST调用,或者是我的尝试. "url"和"token"变量完全相同:

Now here's the POST call in Python, or my attempt at it. The "url" and "token" variables are exactly the same:

import json
import requests

url = <Same URL as above>
token = <same token as above>

data = {
    'operation' : -1,
}
headers = {
    "Authorization": "Token " + token,
}
response = requests.post(url, data=json.dumps(data), headers=headers)

此python请求无法正常工作-应用程序api会显示操作无效,哦,哦."为什么会这样?我不能在请求中正确传递数据参数吗?

This python requests does not work -- the app api prints "Operation was none, uh oh." Why would this happen? Am I not passing my data parameter correctly in the request?

已解决.不要在数据上调用json_dumps,只需按原样传递即可.

Solved. Don't call json_dumps on the data, just pass it in as is.

推荐答案

您无需对data进行JSON编码,因为您无需在视图中使用JSON进行任何操作.只需将您的字典直接传递到data:

You don't need your data to be JSON encoded, as you're not doing anything with JSON in your view. Simply pass your dictionary directly to data:

response = requests.post(url, data=data, headers=headers)

这篇关于Python POST请求找不到数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆