2012-06-17 24 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。

謝謝。