django-rest-framework导致RawPostDataException:您无法访问body

时间:2016-05-20 18:47:22

标签: django-rest-framework

我有这个代码可以正常使用我的ajax请求:

    // client
    $.ajax({
        type: "POST",
        url: "api",
        contentType: "application/json; charset=utf-8",
        headers: {'X-CSRFToken': '{{ csrf_token }}'},
        data: JSON.stringify({
            x: $("#x").val(),
        }),
        success: response,
        dataType: 'json',
        minLength: 0,
    });

# server - views.py:
@staff_member_required
def api(request):
    params = request.POST

但除了ajax方法之外,我还想要一种允许人们使用令牌身份验证的辅助方法,所以我修改了view.py,如下所示:

# server - views.py:
@api_view(['GET', 'POST'])
@authentication_classes((TokenAuthentication, SessionAuthentication, BasicAuthentication))
@permission_classes((IsAuthenticated,))
@staff_member_required
def api(request):
    params = request.POST

和令牌认证客户端代码:

headers = {'Authorization': 'Token {}'.format(mytoken), 'Content-Type': 'application/json'}
response = requests.post(BASE_URL, headers=headers, json=data)

一旦我添加@api_view,我的ajax请求就会导致服务器错误:

ERROR: Internal Server Error: /api
Traceback (most recent call last):
  File "venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "venv/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "venv/lib/python2.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "venv/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch
    response = self.handle_exception(exc)
  File "venv/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch
    response = handler(request, *args, **kwargs)
  File "venv/lib/python2.7/site-packages/rest_framework/decorators.py", line 53, in handler
    return func(*args, **kwargs)
  File "venv/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/mike/mike/myapp/myapp/myapp/views.py", line 422, in api
    params = json.loads(request.body)
  File "venv/lib/python2.7/site-packages/rest_framework/request.py", line 357, in __getattribute__
    return getattr(self._request, attr)
  File "venv/lib/python2.7/site-packages/django/http/request.py", line 231, in body
    raise RawPostDataException("You cannot access body after reading from request's data stream")
RawPostDataException: You cannot access body after reading from request's data stream

1 个答案:

答案 0 :(得分:4)

显然,一旦你使用django-rest-framework,就必须使用

params = request.data

检索数据。 http://www.django-rest-framework.org/api-guide/requests/

感谢django-rest-framework IRC。