Home » Html » Sending a form array to Flask

Sending a form array to Flask

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have a html form with multiple inputs named like this:

<input name="hello[]" type="text" />
<input name="hello[]" type="text" />
<input name="hello[]" type="text" />

In PHP you get this as an array but is it the same way in Python using Flask?

I tried this:

hello = request.form['hello']    
print hello

In Flask, but that did not work, I got a “400 bad request”:

Bad Request

The browser (or proxy) sent a request that this server could not understand.

How do I do it in Flask?

Answers:

You are following a PHP convention of adding brackets to the field names. It’s not a web standard, but because PHP supports it out of the box it is popular; Ruby on Rails also uses it.

If you do use that convention, to get the POST data on the Flask side you need to include the square brackets in the field name. You can retrieve all values of the list using MultiDict.getlist():

hello = request.form.getlist('hello[]')

You don’t have to use the [] convention at all, of course. Not appending the [] to the hello name will work perfectly fine, at which point you’d use request.form.getlist('hello') in Flask.