← Flask tutorial

Flask

Handling Forms

The global request object carries the incoming request's data. request.form holds submitted form fields.

Example: a login route handling both GET and POST

from flask import request

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form["username"]
        return f"Welcome, {username}!"
    return "Please log in."
GET  /login          -> "Please log in."
POST /login (username=Ada) -> "Welcome, Ada!"

By default a route only accepts GET — listing both "GET" and "POST" in methods lets one single view handle showing the empty form (GET, when a visitor first arrives) and processing the submitted data (POST, after they submit it), branching on request.method to tell the two cases apart.

Example
from flask import request

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form["username"]
        return f"Welcome, {username}!"
    return "Please log in."
Output
A GET request returns "Please log in."; a POST with username=Ada returns "Welcome, Ada!"