Django can't access raw_post_data

大憨熊 提交于 2019-12-23 07:26:37

问题


I am experiencing a strange thing with Django, here is my 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).

I set POSTMAN to make a POST request with 'test' in the raw field.

Django returns me 3 different thing (random):

Sometime Django returns 'GET' sometime nothing at all and sometime:

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?

  2. Why does it return me that error?

  3. Why it does not return me the 'test' that I set in the raw field?


回答1:


According to django 1.6 deprecation timeline:

The attribute HttpRequest.raw_post_data was renamed to HttpRequest.body in 1.4. The backward compatibility will be removed – HttpRequest.raw_post_data will no longer work.

The motivation is described in the relevant ticket:

request.raw_post_data is a bad name. It has nothing to do with POST in particular, it's just the body of the HTTP request. This confuses users, and makes it look like Django doesn't understand how HTTP works. We should change the name to request.body and start a deprecation process.

Use request.body:

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

Hope that helps.



来源:https://stackoverflow.com/questions/22368190/django-cant-access-raw-post-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!