85

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?

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
dougiebuckets
  • 2,383
  • 3
  • 27
  • 37
  • 2
    Have you considered looking at the Flask documentation? It's covered in the [quickstart](http://flask.pocoo.org/docs/quickstart/#accessing-request-data). Hint: `request.form["fieldname"]` – kindall Nov 07 '12 at 22:42
  • 1
    Have you read this - http://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 Nov 08 '12 at 07:55
  • You can also do `request.args["myvar"]` to access GET key-values – John Strood Jun 16 '16 at 04:56
  • RTFM comments are my absolute favourite comments :Kappa: – technical_difficulty Mar 26 '18 at 16:20

3 Answers3

182

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.

Amin Golmahalleh
  • 3,585
  • 2
  • 23
  • 36
Jason
  • 4,232
  • 3
  • 23
  • 31
80

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

myvar =  request.form["myvar"]
myvar = request.args["myvar"]
davidism
  • 121,510
  • 29
  • 395
  • 339
user1807534
  • 849
  • 7
  • 3
4

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')
yardstick17
  • 4,322
  • 1
  • 26
  • 33