Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 368
Anirban Roy Das Avatar asked Jan 15 '16 20:01

Anirban Roy Das


1 Answers

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.

like image 55
Martijn Pieters Avatar answered Oct 25 '22 07:10

Martijn Pieters