74
votes

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?

3
Have you considered looking at the Flask documentation? It's covered in the quickstart. Hint: request.form["fieldname"] - kindall
Have you read this - flask.pocoo.org/docs/quickstart ? If not, I would recommend to run through it, because it will explain a lot of the things which are not clear in the beginning. Have fun with Flask ;) - Ignas Butėnas
You can also do request.args["myvar"] to access GET key-values - John Strood
RTFM comments are my absolute favourite comments :Kappa: - technical_difficulty

3 Answers

75
votes

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

myvar =  request.form["myvar"]
myvar = request.args["myvar"]
157
votes

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.

4
votes

Adding more to Jason's more generalized way of retrieving the POST data or GET data

from flask_restful import reqparse

def parse_arg_from_requests(arg, **kwargs):
    parse = reqparse.RequestParser()
    parse.add_argument(arg, **kwargs)
    args = parse.parse_args()
    return args[arg]

form_field_value = parse_arg_from_requests('FormFieldValue')