DRF - access request's POST data

2019-09-18 14:06发布

问题:

I do a request to my local server using postman like this:

As you can see it's a post request. In my view (APIView) I need access to the json data. But when I try:

request.POST
# <QueryDict: {}>    

or

request.data  # ¿?
# AttributeError: 'WSGIRequest' object has no attribute 'data'

The only way I can see the sent data is when I access to

request.body
# '{\n    "token": "6J3qG4Ji2Jw44eIklKvPYxUgclfGRWHZDKG",\n    "city": "Port Orange",\n    "state": "FL",\n    "formatted_address": "Peach Blossom Blvd 5329",\n    "_zip": "32128"\n}'

But this is a 'str'

>>> type(request.body)
<type 'str'>

I an trying to access to the request's data in dispatch() method. I can do this:

req = self.initialize_request(request)

This returns a rest_framework.request.Request object and I can access to request data. But then I can't call

super(FaveoAPIView, self).dispatch(request, *args, **kwargs)

Because I get:

{
  "status_code": 400,
  "object": "Malformed request.",
  "success": false
}

I can'r understand why, I guess that when I call self.initialize_request() something change. Any idea?

回答1:

I believe you should be able to override the initial() method on your view in order to achieve what you're attempting. The docstring from the APIView class reads:

"""
Runs anything that needs to occur prior to calling the method handler.
"""

So, it would look something like:

class FaveoAPIView(APIView):

    def initial(self, request, *args, **kwargs):
        super(FaveoAPIView, self).initial(request, *args, **kwargs)
        # Manipulate request.data to your heart's content here

In APIView, this is called immediately before your method handler.



回答2:

super(FaveoAPIView, self).dispatch(request, *args, **kwargs) will call initialize_request turning the request into a DRF one. This can only be once therefore it'll fail after that.

Instead of fixing a broken solution, could you rather tell us about your actual issue, i.e. why you need to access the requests data before the view itself is called ?