DRF - 访问请求的POST数据 [英] DRF - access request's POST data
问题描述
我使用这样的邮递员向本地服务器请求:
您可以看到这是一个帖子请求。在我看来( APIView
)我需要访问json数据。但是当我尝试:
request.POST
#< QueryDict:{}>
或
request.data#¿
#AttributeError:'WSGIRequest'对象没有属性'data'
唯一的方法我可以看到发送的数据是当我访问
request.body
#'{\\\
token :6J3qG4Ji2Jw44eIklKvPYxUgclfGRWHZDKG,\city:Port Orange,\\\
state:FL,\\\
formatted_address:Peach Blossom Blvd 5329,\_zip 32128\\\
'
但这是一个'str' / code>
>>> type(request.body)
< type'str'>
我试图访问请求的数据在 dispatch()
方法。我可以这样做:
req = self.initialize_request(request)
pre>
这将返回一个
rest_framework.request.Request
对象,我可以访问请求数据。但是我不能调用super(FaveoAPIView,self).dispatch(request,* args,** kwargs)
因为我得到:
{
status_code:400,
object:格式错误的请求,
success:false
}
我不明白为什么,我猜当我调用
self.initialize_request()
某事改变。任何想法?解决方案我相信你应该可以覆盖
initial()
方法,以实现您正在尝试的内容。来自APIView
类的docstring显示为:
在调用方法处理程序之前运行需要发生的任何事情
所以,它看起来像:
class FaveoAPIView(APIView):
def initial
super(FaveoAPIView,self).initial(request,* args,** kwargs)
#操作request.data到你心中的内容
在
APIView
中,这是在您的方法之前立即调用处理程序。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 callsuper(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?解决方案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 theAPIView
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.这篇关于DRF - 访问请求的POST数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!