2010-06-16 75 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