2012-06-17 26 views
6

我有一个非常类似于Django's Querydict bizarre behavior: bunches POST dictionary into a single keyUnit testing Django JSON View的问题。但是,这些线程中的问题/回答都没有真正指出我遇到的具体问题。我试图用Django的测试客户端发送一个嵌套的JSON对象的请求(我用非JSON值的JSON对象很好地工作)。Django测试客户端挤压嵌套的JSON

尝试#1:这是我最初的代码:

response = c.post('/verifyNewMobileUser/', 
     {'phoneNumber': user.get_profile().phone_number, 
     'pinNumber': user.get_profile().pin, 
     'deviceInfo': {'deviceID': '68753A44-4D6F-1226-9C60-0050E4C00067', 'deviceType': 'I'}}) 

正如你所看到的,我有我的请求数据中的嵌套的JSON对象。然而,这是request.POST的样子:

<QueryDict: {u'phoneNumber': [u'+15551234567'], u'pinNumber': [u'4171'], u'deviceInfo': [u'deviceType', u'deviceID']}> 

尝试#2:然后我尝试,将在内容类型的参数如下:

response = c.post('/verifyNewMobileUser/', 
    {'phoneNumber': user.get_profile().phone_number, 
    'pinNumber': user.get_profile().pin, 
    'deviceInfo': {'deviceID': '68753A44-4D6F-1226-9C60-0050E4C00067', 'deviceType': 'I'}}, 
    'application/json') 

而我现在得到对于request.POST是

<QueryDict: {u"{'deviceInfo': {'deviceType': 'I', 'deviceID': '68753A44-4D6F-1226-9C60-0050E4C00067'}, 'pinNumber': 5541, 'phoneNumber': u' 15551234567'}": [u'']}> 

我想要做的就是能够为我的请求数据指定一个嵌套的字典。是否有捷径可寻?

回答

13

对我来说,下面的工作(使用命名参数):

geojson = { 
     "type": "Point", 
     "coordinates": [1, 2] 
    } 

    response = self.client.post('/validate', data=json.dumps(geojson), 
           content_type='application/json') 
+0

JSON.dumps是最好的方法。这应该是被接受的答案。 – boatcoder

6

您的问题表明Django正在将您的请求解释为multipart/form-data而不是application/json。尝试

c.post("URL", "{JSON_CONTENT}", content_type="application/json")

还有一点需要注意的是,Python呈现为字符串时,使用单引号表示字典键/值,而simplejson解析器不喜欢这样做。保持你的硬编码的JSON对象为单引号字符串,利用内幕双引号来解决这个问题...

0

我的解决方法是以下:

在测试方法:

data_dict = {'phoneNumber': user.get_profile().phone_number, 
      'pinNumber': user.get_profile().pin, 
      'deviceInfo': 
       {'deviceID': '68753A44-4D6F-1226-9C60-0050E4C00067', 
        'deviceType': 'I'}}) 

self.client.post('/url/', data={'data': json.dumps(data_dict)}) 

在视图:

json.loads(request.POST['data']) 

这将发送post ['data']作为字符串。在视图中,必须从该字符串中加载json。

谢谢。