You just processed a signup form and want to tell the user “Signup successful!” before sending them to the homepage. The standard way in Flask is flash(): this function stores the message in the session (a signed cookie) so it can be shown on the next request. Combine flash() with redirect() following the Post/Redirect/Get pattern, and you both report success and avoid the resubmit-on-refresh problem when the user hits F5. The only requirement: the app must have a SECRET_KEY.
The Problem
A familiar situation: after handling POST, you render a “success” template directly:
@app.post("/dang-ky")def dang_ky(): ten = request.form.get("ten", "").strip() # ... lưu user `ten` vào database ... return render_template_string("<h1>Đăng ký thành công!</h1>")
It looks fine, but when the user hits F5, the browser asks “do you want to resubmit the form?” — clicking yes sends the form again. For a signup form that means duplicate accounts; for a payment form, a double charge. Conversely, if you redirect() to the homepage with no feedback mechanism, the user has no idea whether the action succeeded or failed.
The Fix
Call flash() before redirecting. The message lives in the session, so it “survives” the redirect, and the template on the landing page just needs to read it with get_flashed_messages():
from flask import (Flask, flash, get_flashed_messages, redirect, render_template_string, request, url_for)app = Flask(__name__)app.secret_key = "doi-key-that-kho-doan" # BẮT BUỘC, nếu không flash() sẽ lỗiBASE = """{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} <ul> {% for category, message in messages %} <li class="{{ category }}">{{ message }}</li> {% endfor %} </ul> {% endif %}{% endwith %}"""@app.get("/")def trang_chu(): return render_template_string(BASE + "<h1>Trang chủ</h1>")@app.route("/dang-ky", methods=["GET", "POST"])def dang_ky(): if request.method == "POST": ten = request.form.get("ten", "").strip() if not ten: flash("Vui lòng nhập tên của bạn.", "danger") return redirect(url_for("dang_ky")) # ... lưu user `ten` vào database ... flash(f"Chào mừng {ten}, đăng ký thành công!", "success") return redirect(url_for("trang_chu")) return render_template_string(BASE + "<form method='post'>...</form>")
Why is this better? First, the Post/Redirect/Get flow completely removes the “resubmit the form?” warning on F5. Second, the category parameter (e.g. "success", "danger") lets you style messages differently with CSS or Bootstrap classes (alert-success, alert-danger). Third, a flash message shows exactly once — reading it removes it from the session, so F5 on the landing page won’t show it again.
One important note: flash() stores the message in the session, so if you forget to set SECRET_KEY, Flask throws RuntimeError: The session is unavailable because no secret key was set. Set the key via an environment variable, don’t hardcode it — see the post on environment-based config management.
Apply It to Your Project
This pattern fits anywhere you redirect after POST: signup, login, password change, saving settings, deleting records. Combined with Flask-WTF it’s even cleaner: when form.validate_on_submit() fails, you flash("Data is invalid, please check again.", "danger") and redirect back to the form, so users see the reason without losing page state. In a real project, put the get_flashed_messages() snippet in your base template so every page gets a message area automatically, no repeated code.
Related Posts
- Flask: Validate Forms Safely with Flask-WTF — Skip Manual request.form Handling
- Flask: Managing Login with Flask-Login — login_required and remember me in 5 Minutes
- Flask: Use the Application Factory (create_app) for Testable, Scalable Apps from Day One
FAQ
Where does flash() store the message?
In Flask’s session — i.e. a signed cookie sent to the browser. That’s why the message survives a redirect but can be read only once: get_flashed_messages() consumes it when it reads it.
What if I forget to set SECRET_KEY?
Flask throws RuntimeError because the session can’t work without a key. Set app.secret_key (best read from an environment variable) before calling flash().
Can I skip the category?
Yes. The default category is "message". Passing a category like "success", "danger", or "warning" is just for categorizing and styling the messages differently in your template.
Can flash() be used for JSON APIs?
Not really. APIs should return JSON directly in the response (e.g. {"message": "..."}), because API clients don’t render templates and don’t read session cookies this way. flash() is for server-rendered HTML apps.
If the user refreshes the landing page, does the message show again?
No. The message was consumed on the first read, so F5 just reloads the page normally — that’s the big difference from hardcoding a message into the template.
References
- Flask documentation — Message Flashing: https://flask.palletsprojects.com/en/stable/patterns/flashing/
