2010-06-16 76 views
1

通過詞典列表我有Python字典看起來像這樣的列表:解析作爲POST參數

sandwiches = [ 
    {'bread':'wheat', 'topping':'tomatoes', 'meat':'bacon'}, 
    {'bread':'white', 'topping':'peanut butter', 'meat':'bacon'}, 
    {'bread':'sourdough', 'topping':'cheese', 'meat':'bacon'} 
] 

我想通過這個作爲POST參數傳遞給另一個Django應用程序。客戶端應用程序需要做什麼來遍歷列表?

我想要做的事,如:

for sandwich in request.POST['sandwiches']: 
    print "%s on %s with %s is yummy!" % (sandwich['meat'], sandwich['bread'], sandwich['topping']) 

但我似乎不具有類型的字典列表時,我的數據到達我的客戶端應用程序。

回答

4

你不說你怎麼發佈到應用程序。我的建議是將字典序列化爲JSON,然後簡單地POST這個。

import json, urllib, urllib2 
data = json.dumps(sandwiches) 
urllib2.urlopen(myurl, urllib.urlencode({'data': data})) 

...並且在接收器:

data = request.POST['data'] 
sandwiches = json.loads(data) 
2

我會使用JSON庫將您的數組的字符串序列化爲單個字符串。將此字符串作爲POST參數發送,並使用相同的庫將字符串解析回Django應用程序中的python數據類型。

http://docs.python.org/library/json.html