How to obtain values of request variables using Python and Flask

Question:

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?

Asked By: dougiebuckets

||

Answers:

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

myvar =  request.form["myvar"]
myvar = request.args["myvar"]
Answered By: user1807534

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.

Answered By: Jason

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')
Answered By: yardstick17
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.