DRF - access request's POST data

…衆ロ難τιáo~ 提交于 2020-01-07 09:03:24

问题


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 ?



来源:https://stackoverflow.com/questions/33745533/drf-access-requests-post-data

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