ajax – django:使用json对象测试基于POST的视图
发布时间:2020-12-16 03:11:31 所属栏目:百科 来源:网络整理
导读:我有一个django应用程序与几个视图通过POST请求接受json对象。 json对象是中等复杂的几层嵌套,所以我使用json库解析raw_post_data,如下所示: def handle_ajax_call(request): post_json = json.loads(request.raw_post_data) ... (do stuff with json que
我有一个django应用程序与几个视图通过POST请求接受json对象。 json对象是中等复杂的几层嵌套,所以我使用json库解析raw_post_data,如下所示:
def handle_ajax_call(request): post_json = json.loads(request.raw_post_data) ... (do stuff with json query) 接下来,我想为这些视图编写测试。不幸的是,我无法弄清楚如何将json对象传递给客户端。以下是我的代码的最简单的版本: 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 ) 当我运行测试,它失败与: AttributeError: 'str' object has no attribute 'items' 如何在Client.post方法中传递JSON对象?
The documentation似乎暗示如果你将一个content_type参数传递给client.post,它会将数据值视为文档并直接POST。所以试试这个:
response = c.post('/ajax/call/',content_type='application/json',data=J_string) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |