简体   繁体   English

Django 无法访问 raw_post_data

[英]Django can't access raw_post_data

I am experiencing a strange thing with Django, here is my views.py:我在使用 Django 时遇到了一件奇怪的事情,这是我的 views.py:

def api(request):
    return HttpResponse("%s %s" % (request.method,request.raw_post_data))

Now I make an HTTP POST with POSTMAN (small app for google chrome).现在我用 POSTMAN(谷歌浏览器的小应用程序)制作一个 HTTP POST。

I set POSTMAN to make a POST request with 'test' in the raw field.我将 POSTMAN 设置为在原始字段中使用 'test' 发出 POST 请求。

Django returns me 3 different thing (random): Django 返回了我 3 个不同的东西(随机):

Sometime Django returns 'GET' sometime nothing at all and sometime:有时 Django 返回 'GET' 有时什么都没有,有时:

AttributeError at /
'WSGIRequest' object has no attribute 'raw_post_data'
Request Method: GET
Request URL:    https://api.mywebsiteurl.com/
Django Version: 1.6.2
Exception Type: AttributeError
Exception Value:    
'WSGIRequest' object has no attribute 'raw_post_data'
Exception Location: /home/spice_dj/spice/views.py in api, line 17
Python Executable:  /usr/bin/python
Python Version: 2.7.3
Python Path:    
['/usr/local/lib/python2.7/dist-packages/South-0.8.4-py2.7.egg',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/home/spice_dj']
Server time:    Wed, 12 Mar 2014 22:51:11 -0400
  1. Why Django returns me 'GET' when I clearly make a POST request?当我明确提出 POST 请求时,为什么 Django 会返回“GET”?

  2. Why does it return me that error?为什么它返回给我那个错误?

  3. Why it does not return me the 'test' that I set in the raw field?为什么它不返回我在原始字段中设置的“测试”?

According to django 1.6 deprecation timeline :根据Django 1.6 弃用时间表

The attribute HttpRequest.raw_post_data was renamed to HttpRequest.body in 1.4.属性HttpRequest.raw_post_data在 1.4 中被重命名为HttpRequest.body The backward compatibility will be removed – HttpRequest.raw_post_data will no longer work.向后兼容性将被删除 - HttpRequest.raw_post_data将不再起作用。

The motivation is described in the relevant ticket :动机在相关票证中描述:

request.raw_post_dat a is a bad name. request.raw_post_dat a 是个坏名字。 It has nothing to do with POST in particular, it's just the body of the HTTP request.它与POST没有任何关系,它只是 HTTP 请求的主体。 This confuses users, and makes it look like Django doesn't understand how HTTP works.这让用户感到困惑,并使它看起来像 Django 不了解 HTTP 的工作原理。 We should change the name to request.body and start a deprecation process.我们应该将名称更改为request.body并开始弃用过程。

Use request.body :使用request.body

def api(request):
    return HttpResponse("%s %s" % (request.method, request.body))

Hope that helps.希望有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM