Frage

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": "john@doe.me"}

but it converts each value to a list like below

{"name": ["John Doe"], "email": ["john@doe.me"]}

Can somebody explain Why is this behavior implemented in tornado? Can't it simply return the value without converting it to a list?

War es hilfreich?

Lösung 3

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.

Andere Tipps

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.

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top