我想构建一个测试中间件的请求,但我不希望 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`
上面的代码将无法通过测试,因为我的中间件需要将数据作为文档传递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')
我想做同样的事情django.test.RequestFactory
.
RequestFactory 内置了对 JSON 负载的支持。您不需要先转储数据。但是你应该将内容类型传递给post
,而不是实例化。
factory = RequestFactory()
data = {'message':'A test message'}
request = factory.post('/a/test/path/', data, content_type='application/json')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)