YouTip LogoYouTip

Flask Message Flashing Api

# Flask Message Flashing API The Message Flashing mechanism in Flask is a simple and effective way to provide feedback to users. It allows you to store a message at the end of one request and access it during the next request (and only the next request). This is ideal for displaying one-time notifications such as "Operation successful" or "Invalid input." Flask stores these flashed messages in the client-side **Session**, and they are automatically cleared once they are retrieved. --- ## The `flash()` Function The `flash()` function is used to record a message. It queues up a message that can then be retrieved during the next request. ### Syntax ```python flash(message, category="message") ``` ### Parameters | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `message` | `str` | *Required* | The actual text content of the message you want to display. | | `category` | `str` | `"message"` | The category of the message. Recommended values include: `message`, `success`, `error`, `warning`, `info`. This is useful for styling messages differently in your templates. | --- ## The `get_flashed_messages()` Function The `get_flashed_messages()` function pulls all flashed messages out of the session and returns them. Once called, the messages are deleted from the session. ### Syntax ```python get_flashed_messages(with_categories=False, category_filter=()) ``` ### Parameters | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `with_categories` | `bool` | `False` | If set to `True`, the function returns a list of `(category, message)` tuples instead of just raw message strings. | | `category_filter` | `iterable` | `()` | An iterable (like a list or tuple) of category names. If provided, only messages matching these categories will be returned. | ### Return Values | Parameter State | Return Value Format | Example | | :--- | :--- | :--- | | `with_categories=False` | A list of message strings | `["msg1", "msg2"]` | | `with_categories=True` | A list of `(category, message)` tuples | `[("success", "msg1"), ("error", "msg2")]` | --- ## Using Flashing in Jinja2 Templates The `get_flashed_messages()` function is registered as a global template function in Flask. This means you can call it directly inside your Jinja2 templates without having to pass it explicitly from your Python code via `render_template`. ### Template Examples #### 1. Displaying All Flashed Messages with Categories ```html {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %}
{{ message }}
{% endfor %} {% endif %} {% endwith %} ``` #### 2. Filtering and Displaying Only Error Messages ```html {% for msg in get_flashed_messages(category_filter=) %}
{{ msg }}
{% endfor %} ``` --- ## Complete Code Example Below is a complete Flask application demonstrating how to flash messages during a form submission and render them in a template. ### Python Application (`app.py`) ```python from flask import Flask, flash, get_flashed_messages, redirect, url_for, request, render_template app = Flask(__name__) # Flask sessions require a secret key to cryptographically sign the session cookie. app.secret_key = "super_secret_key" @app.route("/post", methods=["GET", "POST"]) def create_post(): if request.method == "POST": title = request.form.get("title", "").strip() # Validation logic if not title: flash("Title cannot be empty!", "error") else: flash(f"Post '{title}' published successfully!", "success") return redirect(url_for("create_post")) return redirect(url_for("create_post")) # GET request: Retrieve and display messages messages = get_flashed_messages(with_categories=True) return render_template("post.html", messages=messages) if __name__ == "__main__": app.run(debug=True) ``` --- ## Key Considerations > **Important:** > 1. **Secret Key Required:** Because Flask's message flashing relies on **Sessions**, you must set `app.secret_key` in your application configuration. If you do not set a secret key, Flask will raise a `RuntimeError` when you attempt to flash a message. > 2. **One-Time Use:** Flashed messages are designed to be temporary. Once `get_flashed_messages()` is called during a request, those messages are permanently removed from the session and will not be available on subsequent page reloads.
← Flask Template Rendering ApiFlask Application Globals G Ob β†’