Main Content

Requests in Flask

Archive - Originally posted on "The Horse's Mouth" - 2015-10-11 14:47:51 - Graham Ellis

Your request object contains many fields of information - you can access the query string and the headers as well as individual parameters entered into forms using the GET or the POST methods, or both. There are various layers of dispatch of requests (we can come back to these later) - just look at the example at [here] for our initial example; template is [here].

All the (form) field names and their values:

  fvals = ""
  for name in request.values:
    fvals += name + ": "+ request.values.get(name)


All the elements in the request object:

  fields = ""
  for field in dir(request):
    fields += field + ": " + "\n"


Rendered into the template:

  render_template('requestresponse.html',
    available = fields,
    filled = fvals,
    names = ", ".join(request.values),
    query = request.query_string,
    agent = request.headers.get('User-Agent'))


Here's the output:



When collecting form parameters:
request.args: If you want the parameters in the URL (as per GET)
request.form: If you want the info in the body (as per POST)
request.values: If you want both

Note that request.data isn't filled in from form completion - it's where data comes as a 'fallback' if it's not in a name=value format.

And to control routing, you can use a decorator parameter such as
  @app.route('/add', methods=['POST'])
or
  @app.route('/login', methods=['GET', 'POST'])