How to obtain values of request variables using Python and Flask

PythonVariablesRequestFlask

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

myvar =  request.form["myvar"]

myvar = request.args["myvar"]

Solution 3 - Python

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')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondougiebucketsView Question on Stackoverflow
Solution 1 - PythonJasonView Answer on Stackoverflow
Solution 2 - Pythonuser1807534View Answer on Stackoverflow
Solution 3 - Pythonyardstick17View Answer on Stackoverflow