Reputation: 821
I started working with tornado
recently, one thing which annoys me is its POST
value parsing.
In an example ajax request if I am sending name and email as form data.
the expected data in server is
{ "name": "John Doe", "email": "[email protected]"}
but it converts each value to a list like below
{"name": ["John Doe"], "email": ["[email protected]"]}
Can somebody explain Why is this behavior implemented in tornado? Can't it simply return the value without converting it to a list?
Upvotes: 2
Views: 556
Reputation: 22134
It's not just tornado - this is how the form-urlencoded format is defined. Every argument may appear multiple times and you have no way of knowing whether an argument that appears once was intended to be a single-element list or a single value. To avoid having to think about this, most of your access to the request arguments should go through RequestHandler.get_argument and RequestHandler.get_arguments to make it clear whether you expect a list or a single value.
Upvotes: 1
Reputation: 24007
Tornado supports multiple values for the same parameter name:
http://example.com/page?foo=1&foo=2
This is parsed, obviously, as:
{'foo': ['1', '2']}
Tornado could set each value to a string if there's only one value, and a list of strings if there are multiple values. Then your code must check each value's type before using its contents. But it's far more convenient, and far less error-prone, to wrap all values in lists all the time.
Upvotes: 2
Reputation: 12773
I would imagine this is such that whether the values are lists or not they can be used in a unified way without having to then check if they're a list or not.
E.g. imagine you wanted to do something with name
, but as it can sometimes be a list and sometimes a single value, every time you worked with name
you'd have to include something like
if isinstance(name, list):
# Handle the list
else:
# Handle a string
Instead, you can access name[0]
without worrying that you might be accessing the first character of a string.
Disclaimer
I am not a Tornado developer; you'd have to ask them for the reason they went with this convention to be sure.
Upvotes: 2