Skip to main content
 首页 » 编程设计

python之解析作为 POST 参数传递的字典列表

2025年05月04日20insus

我有一个 python 字典列表,如下所示:

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']) 

但是当我的数据到达我的客户端应用程序时,我似乎没有字典列表。

请您参考如下方法:

你没有说明你是如何发布到应用程序的。我的建议是将字典序列化为 JSON,然后简单地发布它。

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

... 在接收器上:

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