使用Django RequestFactory而不是表单数据的POST文档 [英] POST document with Django RequestFactory instead of form data

查看:35
本文介绍了使用Django RequestFactory而不是表单数据的POST文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个测试中间件的请求,但是我不希望POST请求总是假设我正在发送表单数据.

I'd like to build a request for testing middleware, but I don't want POST requests to always assume I'm sending form data. Is there a way to set request.body on a request generated from django.test.RequestFactory?

即,我想做类似的事情:

I.e., I'd like to do something like:

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 始终将数据作为表单数据发送.

The code above will fail the test because my middleware needs the data to be passed as the document in request.body not as form data in request.POST. However, RequestFactory always sends the data as form data.

我可以使用 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 ,而不是实例化.

RequestFactory has built-in support for JSON payloads. You don't need to dump your data first. But you should be passing the content-type to post, not to the instantiation.

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

这篇关于使用Django RequestFactory而不是表单数据的POST文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆