使用Django RequestFactory而不是表单数据的POST文档

Jay*_*Jay 3 python testing django

我想建立一个测试中间件的请求,但我不希望POST请求总是假设我正在发送表单数据.有没有办法设置request.body生成的请求django.test.RequestFactory

即,我想做类似的事情:

from django.test import RequestFactory
import json

factory = RequestFactory(content_type='application/json')
data = {'message':'A test message'}
body = json.dumps(data)
request = factory.post('/a/test/path/', body)

# And have request.body be the encoded version of `body`
Run Code Online (Sandbox Code Playgroud)

上面的代码将无法通过测试,因为我的中间件需要将数据作为文档传递而request.body不是作为表单数据传递request.POST.但是,RequestFactory始终将数据作为表单数据发送.

我可以这样做django.test.Client:

from django.test import Client
import json

client = Client()
data = {'message':'A test message'}
body = json.dumps(data)
response = client.post('/a/test/path/', body, content_type='application/json')
Run Code Online (Sandbox Code Playgroud)

我想做同样的事情django.test.RequestFactory.

Dan*_*man 6

RequestFactory内置了对JSON有效负载的支持.您不需要先转储数据.但是你应该将内容类型传递post给实例,而不是实例化.

factory = RequestFactory()
data = {'message':'A test message'}
request = factory.post('/a/test/path/', data, content_type='application/json')
Run Code Online (Sandbox Code Playgroud)

  • 嗯。当我删除 content_type="application/json" 时,request.POST 有内容。 (2认同)