DRF - 访问请求的POST数据

时间:2015-11-16 22:08:29

标签: django django-rest-framework django-class-based-views

我使用这样的邮递员向我的本地服务器发出请求:

POSTMan post request

正如您所看到的,它是一个帖子请求。在我看来(APIView)我需要访问json数据。但是当我尝试:

request.POST
# <QueryDict: {}>    

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

我可以看到发送数据的唯一方法是访问

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

但这是'str'

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

我试图以dispatch()方法访问请求的数据。我可以这样做:

req = self.initialize_request(request)

这会返回一个rest_framework.request.Request对象,我可以访问请求数据。但后来我无法致电

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

因为我得到了:

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

我可以理解为什么,我想当我打电话给self.initialize_request()时会发生一些变化。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我相信您应该能够覆盖视图中的initial()方法,以实现您的尝试。 APIView类的docstring写道:

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

所以,它看起来像是:

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

APIView中,这会在您的方法处理程序之前立即调用。

答案 1 :(得分:0)

super(FaveoAPIView, self).dispatch(request, *args, **kwargs)会致电initialize_request将请求转为DRF。这只能是一次,因此它会在那之后失败。

您是否可以告诉我们您的实际问题,而不是修复损坏的解决方案,即在调用视图本身之前需要访问请求数据的原因?

相关问题