I have a list of python dictionaries that look like this:
sandwiches = [
{'bread':'wheat', 'topping':'tomatoes', 'meat':'bacon'},
{'bread':'white', 'topping':'peanut butter', 'meat':'bacon'},
{'bread':'sourdough', 'topping':'cheese', 'meat'开发者_开发知识库:'bacon'}
]
I want to pass this as a POST parameter to another Django app. What does the client app need to do to iterate through the list?
I want to do something like:
for sandwich in request.POST['sandwiches']:
print "%s on %s with %s is yummy!" % (sandwich['meat'], sandwich['bread'], sandwich['topping'])
But I don't seem to have a list of dicts when my data arrives at my client app.
You don't say how you're POSTing to the app. My advice would be to serialize the dictionaries as JSON, then simply POST that.
import json, urllib, urllib2
data = json.dumps(sandwiches)
urllib2.urlopen(myurl, urllib.urlencode({'data': data}))
... and on the receiver:
data = request.POST['data']
sandwiches = json.loads(data)
I would use the JSON libraries to serialize your array of dicts into a single string. Send this string as a POST param, and parse the string back into the python datatypes in the Django app using the same library.
http://docs.python.org/library/json.html
firstly make string of the list
import ast, requests
# request send code
dev_list = [{"1": 2}, {"2": 4}]
str_list = str(dev_list) # '[{"1": 2}, {"2": 4}]'
data = {"a" : "mynema",
'str_list': str_list
}
requests.post(url, data )
#request receive side
data = request.data
dev_list = data.get('str_list')
dev_list = ast.literal_eval(dev_list)
#dev_list --> [{"1": 2}, {"2": 4}]
Now you receive list of dictionary.
精彩评论