← 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!"
Ready to go further?

These free tutorials are a preview, our Backend Development cohort covers it in depth, with a real project and a cohort alongside you. Closes Nov 30

Enroll in Backend Development

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account