Tornado - What is the difference between RequestHandler's get_argument(), get_query_argument() and get_body_argument()?
Asked Answered
T

1

10

When to use RequestHandler.get_argument(), RequestHandler.get_query_argument() and RequestHandler.get_body_argument()?

What is the use-case for each of them?

Also what does the request.body and request.argument do in these cases? Which are to be used in which scenarios?

And, is there a request.query or something similar too?

Taunyataupe answered 15/1, 2016 at 20:4 Comment(0)
L
20

Most HTTP requests store extra parameters (say, form values) in one of two places: the URL (in the form of a ?foo=bar&spam=eggs query string), or in the request body (when using a POST request and either the application/x-www-form-urlencoded or multipart/form-data mime type).

The Request.get_query_argument() looks for URL parameters, the RequestHandler.get_body_argument() lets you retrieve parameters set in the POST body. The RequestHandler.get_argument() method retrieves either a body or a URL parameter (in that order).

You use Request.get_argument() when you explicitly don't care where the parameter comes from and your endpoint supports both GET and POST parameters. Otherwise, use one of the other methods, to keep it explicit where your parameters come from.

The Request.get_*_argument methods use the request.body_arguments and request.query_arguments values (with request.arguments being their aggregate), decoded to Unicode. request.body is the undecoded, unparsed raw request body; and yes, there is an equivalent self.query containing the query string from the URL.

Lyophilize answered 15/1, 2016 at 20:23 Comment(7)
@martin-pieters Thanks Martin. What about the second part? what is the difference between request.body and request.argument? and is there any request.query?Taunyataupe
@AnirbanRoyDas: sorry, missed that, added now.Lyophilize
Finally got it. I have added another question, if you find time then please have a look #34822240Taunyataupe
This answer should just be copied to the documentation! Very helpful, thanks.Minim
Does tornado parse JSON format body with get_body_argument()? and what's the difference with get_*_argument() and get_*_arguments()?Taxis
@JasonXie there is no JSON support, no. Query and POST parameters can appear multiple times (foo=42&foo=81); get_*_arguments() returns a list with all values for a given parameter, get_*_argument() returns just the last value if there are is more than one.Lyophilize
Wow, that was not obvious at all from the docs I was reading, so thanks for this. If only query arguments had a less generic name.Spherical

© 2022 - 2024 — McMap. All rights reserved.