Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain values of request variables using Python and Flask [duplicate]

I'm wondering how to go about obtaining the value of a POST/GET request variable using Python with Flask.

With Ruby, I'd do something like this:

variable_name = params["FormFieldValue"] 

How would I do this with Flask?

like image 536
dougiebuckets Avatar asked Nov 07 '12 22:11

dougiebuckets


People also ask

How do you get the request object in Flask?

To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things.

How do you request parameters on a Flask?

In the first one we would use request. args. get('<argument name>') where request is the instance of the class request imported from Flask. Args is the module under which the module GET is present which will enable the retrieve of the parameters.

How do you handle a request in Flask?

By default, the Flask route responds to GET requests. However, you can change this preference by providing method parameters for the route () decorator. To demonstrate the use of a POST method in a URL route, first let us create an HTML form and use the POST method to send form data to the URL.


2 Answers

If you want to retrieve POST data:

first_name = request.form.get("firstname") 

If you want to retrieve GET (query string) data:

first_name = request.args.get("firstname") 

Or if you don't care/know whether the value is in the query string or in the post data:

first_name = request.values.get("firstname")  

request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.

like image 193
Jason Avatar answered Sep 29 '22 18:09

Jason


You can get posted form data from request.form and query string data from request.args.

myvar =  request.form["myvar"] 
myvar = request.args["myvar"] 
like image 39
user1807534 Avatar answered Sep 29 '22 17:09

user1807534