Django的:测试后根据使用JSON对象的意见 [英] django: Testing POST-based views with json objects
问题描述
我有接受通过POST请求JSON对象几点看法Django应用程序。 JSON的对象是中等复杂与嵌套几层,所以我使用JSON库解析raw_post_data,如下所示:
I have a django application with several views that accept json objects via POST requests. The json objects are medium-complex with a few layers of nesting, so I'm using the json library to parse raw_post_data, as shown here:
def handle_ajax_call(request):
post_json = json.loads(request.raw_post_data)
... (do stuff with json query)
接下来,我要编写测试这些意见。不幸的是,我无法弄清楚如何将JSON对象传递给客户。下面是我的code一个最简单的情况下版本:
Next, I want to write tests for these views. Unfortunately, I can't figure out how to pass the json object to the Client. Here's a simplest-case version of my code:
def test_ajax_call(self):
c = Client()
call_command('loadfixtures', 'temp-fixtures-1') #Custom command to populate the DB
J = {
some_info : {
attr1 : "AAAA",
attr2 : "BBBB",
list_attr : [ "x", "y", "z" ]
},
more_info : { ... },
info_list : [ 1, 22, 23, 24, 5, 26, 7 ]
}
J_string = json.dumps(J)
response = c.post('/ajax/call/', data=J_string )
当我运行测试,它失败:
When I run the test, it fails with:
AttributeError: 'str' object has no attribute 'items'
如何传递JSON对象的Client.post方法?
How can I pass the JSON object in the Client.post method?
推荐答案
的 似乎暗示该文件,如果你传递一个 CONTENT_TYPE
参数 client.post
,它将把数据
值作为一个文档并直接张贴。因此,尝试这样的:
The documentation seems to imply that if you pass a content_type
parameter to client.post
, it will treat the data
value as a document and POST it directly. So try this:
response = c.post('/ajax/call/', content_type='application/json', data=J_string)
这篇关于Django的:测试后根据使用JSON对象的意见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!