Django Rest Framework APIRequestFactory请求对象没有属性'query_params' [英] Django Rest Framework APIRequestFactory request object has no attribute 'query_params'
问题描述
class Dummy(APIView):
def get(self,request) :
return Response(data = request.query_params.get('uuid'))
要测试它,我需要创建一个请求对象,以传入 get
函数
def test_dummy(self):
来自rest_framework.test import APIRequestFactory
factory = APIRequestFactory()
request = factory.get('/?uuid = abcd')
DummyView()。get(request)
它抱怨 AttributeError: WSGIRequest对象没有属性'query_params'
仔细看看,工厂创建一个 WSGIRequest
实例,而不是DRF版本< class'rest_framework.request.Request'>
。
>>>来自rest_framework.test import APIRequestFactory
>>> factory = APIRequestFactory()
>>> request = factory.get('/')
>>>请求.__ class__
< class'django.core.handlers.wsgi.WSGIRequest'>
没错。现在, APIRequestFactory
返回一个 HttpRequest
对象,它只能升级到一个REST框架请求
对象一旦到达视图层。
这反映了您在实际请求中看到的行为,以及它是什么> 做处理例如。渲染JSON,XML或您为测试请求配置的任何其他内容类型。
但是,我同意这是令人惊讶的行为,在某些时候它可能会返回一个 Request
对象,REST框架视图将确保它只执行 Request
c> HttpRequest 。
您需要做的事情是实际调用视图,而不是调用 .get()
方法...
factory = APIRequestFactory )
request = factory.get('/?uuid = abcd')
view = DummyView.as_view()
response = view(request)#调用视图,不调用`.get ()`
Lets say I have this APIView
class Dummy(APIView):
def get(self, request):
return Response(data=request.query_params.get('uuid'))
To test it, I need to create a request object to pass into the get
function
def test_dummy(self):
from rest_framework.test import APIRequestFactory
factory = APIRequestFactory()
request = factory.get('/?uuid=abcd')
DummyView().get(request)
It complains about AttributeError: 'WSGIRequest' object has no attribute 'query_params'
Having a closer look, the factory creates a WSGIRequest
instance instead of a DRF version <class 'rest_framework.request.Request'>
.
>>> from rest_framework.test import APIRequestFactory
>>> factory = APIRequestFactory()
>>> request = factory.get('/')
>>> request.__class__
<class 'django.core.handlers.wsgi.WSGIRequest'>
That's right. At the moment APIRequestFactory
returns an HttpRequest
object, which only get upgraded to a REST framework Request
object once it gets to the view layer.
This mirrors the behavior that you'll see in an actual request, and what it does do is deal with eg. rendering JSON, XML or whatever other content type you have configured for your test requests.
However I agree that it's surprising behavior and at some point it will probably return a Request
object, and the REST framework view will ensure that it only performs the Request
upgrade on requests that instances of HttpRequest
.
What you need to do in your case is actually call the view, rather than invoking the .get()
method...
factory = APIRequestFactory()
request = factory.get('/?uuid=abcd')
view = DummyView.as_view()
response = view(request) # Calling the view, not calling `.get()`
这篇关于Django Rest Framework APIRequestFactory请求对象没有属性'query_params'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!