Parse POST data containing square brackets in Python?

1k views Asked by At

I'm writing a python webapp (on Google AppEngine, using webob) that should process a form containing a list of addresses.

To simplify, lets say the form contains these inputs:

  <input type="hidden" name="address[]" value="1" />
  <input type="hidden" name="address[]" value="2" />
  <input type="hidden" name="address[]" value="3" />
  <input type="hidden" name="address[]" value="4" />

Now, Rails\PHP would parse this to a single 'address' value containing a list [1,2,3,4]. Is there a simple way to do this in Python?

2

There are 2 answers

3
Greg On

from inside a RequestHandler method, self.request.params.getall('address[]') will return a list of the values. The [] is of no significance though, the fields could just as easily be named 'address'.

0
X-Istence On

WebOb uses something called a MultiDict. self.request.POST will take an appropriately form encoded request and return a MultiDict.

From this MultiDict you can call .getall() with the name of a key, in this case your key would be "address[]".

To get a list of entries you would call:

self.request.POST.getall('address[]')

It is not required that you use address[] as the name as MultiDict doesn't use that to identify whether a key can exist multiple times or not.