Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 72 ยท Forms and User Input

Flash Messages

Learn how Flask flash messages show a one-time notice after a redirect, how categories work, why SECRET_KEY is required, and how to render flashes in a layout.

A flash message is a short note that you store during one request and show during the next one, exactly once. It is the standard way to say "Profile saved" or "Wrong password" after a form submission. The usual flow is: handle a POST, call flash(), redirect, and let the page you land on display the message.

Flash messages solve a specific problem. After a successful POST you should redirect (the Post/Redirect/Get pattern), but a redirect starts a brand new request, and your view has no way to hand a sentence to it. Flask's answer is to park the message in the session, a signed cookie, and delete it as soon as it has been read.

flash() and get_flashed_messages()

Two functions do all the work:

  • flash(message, category="message") queues a message for the user.
  • get_flashed_messages() returns the queued messages and removes them. It is available in every Jinja template automatically, and you can import it in Python too.

Because the messages travel inside the session cookie, your app needs a SECRET_KEY to sign it. Without one, Flask cannot create a session and flash() raises an error. The first example shows both the failure and the fix:

Python flash() needs a secret key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first request to /read returns the message and the second returns an empty list. Reading flashes empties them from the session, which is what makes them one-time messages. (Inside a single request, repeated calls return the same list, so a layout and a partial template can both ask for it.)

Use a long random SECRET_KEY in real projects and keep it out of your source code (see Configuration). Anyone who knows the key can forge session cookies, flash messages included.

The life of a flash message

Here is what happens across the two requests:

sequenceDiagram
    participant B as Browser
    participant F as Flask
    B->>F: POST /profile (form data)
    F->>F: flash("Profile saved")
    F-->>B: 302 redirect + Set-Cookie (session with message)
    B->>F: GET /profile (cookie sent back)
    F->>F: get_flashed_messages() reads and clears
    F-->>B: 200 page with notice + Set-Cookie (session emptied)
    B->>F: GET /profile (refresh)
    F-->>B: 200 page without notice

A flash lives in the session cookie from the redirect until the next page reads it.

Reloading the page after that does not bring the message back. That is intentional: the notice described an event, and the event is over.

Showing flashes in a layout

Render flashes once, in your base template, so every page gets them for free. Here is a typical block using with_categories=true (more on categories below). Pages that extend the layout (see Template inheritance) would not need to repeat it:

HTML
{% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
    <ul class="flashes">
      {% for category, message in messages %}
        <li class="flash {{ category }}">{{ message }}</li>
      {% endfor %}
    </ul>
  {% endif %}
{% endwith %}

The message is printed with {{ message }}, so Jinja's autoescaping protects you if a flash contains user input such as a name. Do not mark flash text as |safe unless you wrote it yourself.

Categories

The second argument to flash() is a category, a plain string. The default is "message". Categories let your template style a success differently from an error, for instance with different CSS classes. Common choices are success, info, warning and danger (or error).

get_flashed_messages() has two options for categories:

  • with_categories=True returns (category, message) tuples instead of bare strings.
  • category_filter=["error"] returns only messages in the listed categories, leaving the others queued for a later call.
Python Categories and filters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The page prints each category in brackets, and a second visit to /page is empty because the first one consumed the flashes. The last call shows category_filter pulling out only the error text.

Flashing in a real flow

Now put it together with the pattern you will use constantly: a form view that validates input, flashes the result and redirects. The test client follows the redirect so you can watch the message appear once and disappear:

Python Post, flash, redirect, show once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each POST answers with a 302, the client requests the page again carrying the cookie, and the page shows the notice. The final plain GET has nothing to show.

Things to know

  • Cookie size. The whole session, flashes included, must fit in a cookie of about 4 KB. Flash short sentences, not documents.
  • Redirects matter. If you flash and then render a template in the same request, the message is shown on that page right away. If the template never calls get_flashed_messages(), the message lingers in the session until some later page does. Flash right before a redirect to a page that renders them.
  • Not per page. Flashes belong to the user's session, not to a URL. Whichever page next calls get_flashed_messages() receives them, so keep the call in the base layout.
  • No JSON APIs. API clients have no cookie jar to carry messages. Return the status and an error body instead (see JSON APIs).
  • Testing. The test client keeps cookies between requests, so flashes survive a redirect there just like in a browser. Use with client.session_transaction() as s: to inspect s["_flashes"] directly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to flashed messages after get_flashed_messages() returns them?

    Reading flashes empties them. That is what makes a flash a one-time notice.
  2. 2. Calling flash() raises a RuntimeError about the session. What is the most likely cause?

    Flashes are stored in the signed session cookie, and Flask cannot sign it without a secret key.
  3. 3. How do you get both the category and the text for each flashed message?

    with_categories=True returns (category, message) tuples. category_filter only selects which categories to return.
  4. 4. Where should you usually call get_flashed_messages() so every page can show notices?

    Putting it in the shared layout means any page the user lands on after a redirect can display the pending messages.

Summary

  • flash(message, category) queues a one-time message in the session; get_flashed_messages() returns it and clears it.
  • Flashing needs SECRET_KEY, because the session is a signed cookie.
  • Flash right before a redirect so the next page shows the message.
  • Categories (success, info, warning, error) let templates style messages; use with_categories=True to read them and category_filter to select some.
  • Render flashes once in the base layout and keep autoescaping on.
  • Flashes are small and tied to the session, so they are for browser pages, not JSON APIs.

Next: File Uploads, receiving files from a form safely.