liveBook · Manning

Cookie

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

A cookie is client-side data exchanged with a web server on subsequent requests to retain information or identify a client.

A blog can show posts to everyone while allowing only known users to add posts or comments. But each HTTP request arrives separately: how does the server remember who logged in? A session cookie gives the browser a value to send with later requests, allowing the server to connect those requests to a user and their information. section 8.1.1 section 8.2

The server creates a session explicitly, then sends its cookie in a response. Later requests include the cookie. A unique identifier links those requests to user information, such as a name or shopping cart. In Flask, a configured SECRET_KEY cryptographically signs the session cookie: its contents can be viewed in the browser, but cannot be modified without that key. Keep the key strong and private. section 8.1.1

Remembering a login

A login route validates the submitted form, finds the user by email, and checks the password. On success, Flask-Login records the login and creates a session cookie. The identifier lets a user loader retrieve the corresponding User record on later requests; the application can then reserve posting and commenting for known users. A failed login instead displays a warning and returns to the login screen. section 8.2 section 8.2.1

Cookies also need a deliberate end. By default, a Flask session cookie lasts until the browser closes; a permanent session can be given a longer lifetime. Logging out is a separate action: the logout route calls logout_user(), resets the session cookie, and redirects to a page available to everyone. Together, login and logout make the cookie useful for remembering a user without treating every visitor as authenticated. section 8.1.1 section 8.4.3

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

How deep it goes
Works through creation, signing, request reuse, lifetime, login, and logout; defers detailed database treatment.
Examples
Uses a blog login flow, a user record, restricted posts and comments, and a logout route.
What it assumes
Assumes familiarity with Python route handlers, forms, and HTTP requests while explaining how a session cookie preserves state.
What you can do after
Apply it via Flask and Flask-Login to remember authenticated users across requests and log them out.
How it connects
Links cookies to HTTP sessions, authentication, user identifiers, Flask-Login, and access control.

Also explained in

Compare how 10 books explain cookie →

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.