Retrieving Array Passed in through HTML Form

1,383 views
Skip to first unread message

Aaron

unread,
Jan 8, 2010, 1:43:22 AM1/8/10
to Tornado Web Server
Hey All,

I'm new to Tornado, so please bear with me. I am passing in an array
via an HTML form like so:

<input type="text" name="recipient[]" value="1">
<input type="text" name="recipient[]" value="2">

I would like to retrieve this when posted to my requesthandler. What
is the correct syntax to use for this? I'm unable to find this in the
documentation anywhere. I have tried the following:

self.get_argument("recipient",[])
self.request.POST.getlist("recipient")

But, neither works.

All the best. Thanks in advance.

Matt F

unread,
Jan 8, 2010, 2:10:34 AM1/8/10
to Tornado Web Server
Aaron,

First thing's first, you don't need to name your input with a [].
Short story shorter, you're just making things more confusing for
yourself.

The request dict stores all of the values in a Python list (what
you're referring to as an array). So, for instance, your request
would look like:

{ "recipient": ["1", "2"] }

(for reference, even a normal request with only one value per argument
would be { "foo": ["bar"] }. If you want to see for yourself, put
"print self.request.arguments" in your post handler somewhere and take
a look at the console.)

Calling self.get_argument("recipient") grabs the last item off that
list (in the -1 position) and returns that to you. So in the case
where you have multiple items in that list, you're only going to get
the last one. If you want to actually grab the list, you have to go
into the arguments dict yourself and retrieve it, which is really
easy. You can do so by:

self.request.arguments.get("recipient") which will return ["1", "2"]
(or self.request.arguments["recipient"], but using the get method
allows you to set a default value in the case the key doesn't exist)

Hope that helps.

Aaron

unread,
Jan 8, 2010, 2:16:01 AM1/8/10
to Tornado Web Server
Wow, that seems so obvious now that you mention it. Thanks!

Matt F

unread,
Jan 8, 2010, 2:21:01 AM1/8/10
to Tornado Web Server
It's a common confusion, logically you wouldn't think of a single
value in a dictionary being stored in a list.
Reply all
Reply to author
Forward
0 new messages