django-rest-framework causes RawPostDataException:

2019-08-14 08:19发布

问题:

I have this code that works fine with my ajax request:

    // 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

but in addition to the ajax approach, I want a secondary approach to allow people use token authentication so I modified the view.py as below:

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

and the token authentication client code:

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

As soon as I add @api_view, my ajax request causes a server error:

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:

Apparently once you use django-rest-framework, you'll have to use

params = request.data

to retrieve data. http://www.django-rest-framework.org/api-guide/requests/

Thanks to django-rest-framework IRC.