0
0
Flaskframework~5 mins

Accessing form data in routes in Flask

Choose your learning style9 modes available
Introduction

We use form data in routes to get information users type into a web form. This helps the app respond to user input.

When a user submits a login form with username and password.
When a visitor fills out a contact form on a website.
When a user posts a comment or feedback on a blog.
When a user uploads data through a form to update their profile.
Syntax
Flask
from flask import request

@app.route('/submit', methods=['POST'])
def submit():
    value = request.form['field_name']
    # use value as needed

request.form holds form data sent by POST method.

You can access form fields by their name attribute.

Examples
Get the value of the form field named 'username'.
Flask
username = request.form['username']
Get 'email' field value or use a default if missing.
Flask
email = request.form.get('email', 'no-email@example.com')
Check if password was provided and handle missing data.
Flask
password = request.form.get('password')
if not password:
    return 'Password is required', 400
Sample Program

This Flask app shows a login form on GET. On POST, it reads username and password from the form data and greets the user if both are provided.

Flask
from flask import Flask, request

app = Flask(__name__)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        if username and password:
            return f'Welcome, {username}!'
        else:
            return 'Missing username or password', 400
    return '''
        <form method="post">
            Username: <input type="text" name="username"><br>
            Password: <input type="password" name="password"><br>
            <input type="submit" value="Login">
        </form>
    '''
OutputSuccess
Important Notes

Always check if form fields exist to avoid errors.

Use request.form.get() to safely access fields with a default.

Form data is only available for POST or PUT requests, not GET.

Summary

Use request.form to get data users send via forms.

Access fields by their name attribute.

Check for missing data to handle errors gracefully.