liveBook · Manning

Session management

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

Session management is the handling of state that associates successive requests with a user or client interaction.

A user should not have to prove who they are on every page of a blog. Session management connects a successful login to later requests. In a Flask application, flask_login provides login and logout tools, “remember me” functionality, and protection for endpoints that require an authenticated user. section 8.2.1

The login flow puts that continuing identity in context:

  • A GET request displays the login form; submitting it sends a POST request. section 8.2.1
  • The application checks the submitted email and password against its User model. On a match, it sends the user home or to the page they originally requested. section 8.2.1
from logging import getLogger
from flask import render_template, redirect, url_for, request
from . import auth_bp                                            #1
from ..models import db_session_manager, User                    #2
from .. import login_manager                                     #3
from .forms import LoginForm                                     #4
from flask-login import login_user, logout_user, current_user
from werkzeug.urls import url_parse
 
logger = getLogger(__name__)
 
@login_manager.user_loader                                       #5
def load_user(user_id):                                          #5
    with db_session_manager() as db_session:                     #5
        return db_session.query(User).get(user_id)               #5
 
@auth_bp.route("/login", methods=["GET", "POST"])                #6
def login():
    form = LoginForm()
    if form.validate_on_submit():
        with db_session_manager() as db_session:                 #7
            user = db_session.query(User)
            .filter(User.email == form.email.data)
            .one_or_none()                                     #8
            if user is None or not                               #9
            user.verify_password(form.password.data):          #9
                flash("Invalid email or                          #9
                password", "warning")                          #9
                return redirect(                                 #9
                [url_for("auth_bp.login"))                     #9
            login_user(user,                                     #10
            remember=form.remember_me.data)                    #10
            next = request.args.get("next")                      #10
            if not next or                                       #10
            url_parse(next).netloc != "":                      #10
                next = url_for("intro_bp.home")                  #10
            return redirect(next)                                #10
    return render_template("login.html", form=form)

The authentication route sits alongside a flask_login user loader that retrieves a User by ID. This connects request handling to the application’s stored users. section 8.2.1

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Works through a login sequence and shows integration points, but does not explain session storage internals.
Examples
Uses a blog login form, GET and POST requests, a user loader, and a redirect after successful authentication.
What it assumes
Assumes familiarity with Flask routes, forms, and a database-backed User model while spelling out the login sequence.
What you can do after
Apply it via flask_login to support login, logout, “remember me,” and authenticated endpoints.
How it connects
Connects session management to authentication, protected endpoints, user models, and password hashing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.