Written by Sean Behan on Sun Nov 04th 2018

Ruby on Rails does a great job of parsing arrays in form data and populating a params hash, for quick and easy access in your controllers.

For instance

<input name="item[]" value="item 1"/> <input name="item[]" value="item 2"/>

Gives you

params[:item] # => ["item 1", "item 2"]

Flask doesn't do this work for you. It doesn't even recognize the "[]" syntax on input names. Rails, Sinatra and even PHP do this for you by default.

In Flask you need to do this your self. It isn't difficult though. Here is the code

Assuming you have HTML (notice I skip the form array syntax "[]")

<input name="item" value="item 1"/> <input name="item" value="item 2"/>

And the Python code to populate params hash is...

names = ['item']
params = []
[params.append( request.form.getlist(x) ) for x in names]
params = [dict(zip(names, x)) for x in (zip(*params))]

Returns an array of dictionary objects properly mapped.

The key here is using the getlist() method on the reqest.form object. This returns an array of all the items with name as the argument. Then all you have to do is zip and dict it up with the names you're expecting... I put them into a variable as a list so it's a little less verbose.

Also, notice you don't need to use the "[]" syntax to get an array from getlist(). But if you do want to use that syntax in your forms, you will have to include it in the name you supply to getlist() method.


Tagged with..
#python #flask #params #dictionary #hash #ruby #rails #forms

Just finishing up brewing up some fresh ground comments...