flask icon indicating copy to clipboard operation
flask copied to clipboard

Flash is not working if used after session

Open Nikkie-game-dev opened this issue 6 years ago • 4 comments

Expected Behavior

I should be able to log out a username with session.pop('_usern') and display a "goodbye" message with flash.

session.pop('_usern')
flash(u"Goodbye", 'info')
return redirect(url_for("index"))

Actual Behavior

It does display the message, but it does not pop "_usern" from session.

Environment

  • Python version: 3.8
  • Flask version: 1.1.2
  • Werkzeug version: 1.0.1

Nikkie-game-dev avatar Jun 15 '20 18:06 Nikkie-game-dev

I don't see how that is possible using the code you posted. As you can see here. flash() only sets _flashes in the session, so popping the username should happen regardless.

Please provide a minimal runnable example that reproduces your issue

ThiefMaster avatar Jun 15 '20 18:06 ThiefMaster

This is a very quick app that I have created to showcase the error:

Python:

from flask import (
    Flask,
    session,
    render_template,
    flash,
    get_flashed_messages,
    url_for,
    redirect,
    request,
)

app = Flask(__name__)
app.config["SECRET_KEY"] = "exampleSecretKey"


@app.route("/")
def hello():
    if session.get("_usern") != None:
        return "You are logged in"
    if session.get("_usern") == None:
        return "you are not logged in"


@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("hello.html")
    if request.method == "POST":
        usern = request.form["username"]
        session["_usern"] = usern
        flash(u"welcome", "info")
        return redirect(url_for("hello"))


@app.route("/logout")
def logout():
    session.pop("_usern")
    flash(u"Goodbye", "info")
    return redirect(url_for("hello"))

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>example page</title>
</head>
<body>
    {% with messages = get_flashed_messages(with_categories=true) %}
      {% if messages %}
        <ul class=flashes>
        {% for category, message in messages %}
            <li class="{{ category }}">{{ message }}</li>  
        {% endfor %}
        </ul>
      {% endif %}
    {% endwith %}
    <form method="POST">
        <div class="form-group">
            <label for="username"></label>
            <input type="username" name="username" id="username" aria-describedby="username" placeholder="Some_Username">
            <small id="username" class="form-text text-muted">Insert your Username</small>
        </div>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

I am now not getting any flash, but on logout I get a KeyError 23 if I try to many times the login and logout process. Also, the session.pop returns a value of <SecureCookieSession {'_flashes': [('info', 'welcome'), ('info', 'welcome'), ('info', 'welcome'), ('info', 'welcome'), ('info', 'welcome'), ('info', 'Goodbye'), ('info', 'welcome'), ('info', 'Goodbye'), ('info', 'welcome'), ('info', 'Goodbye'), ('info', 'welcome'), ('info', 'Goodbye'), ('info', 'welcome'), ('info', 'Goodbye'), ('info', 'welcome')]}> if I use the VScode debugger. I think it might be confusing session.pop with flash.

Nikkie-game-dev avatar Jun 15 '20 19:06 Nikkie-game-dev

I also get a value of <SecureCookieSession {'_flashes': [('category', 'message') in the original application.

Nikkie-game-dev avatar Jun 15 '20 19:06 Nikkie-game-dev

Hi, I tested your code, but can't reproduce your issue, the session pop behavior is normal. Here are some tips for your code:

  • You can't repeat visit the logout view, the second visit will throw out KeyError exception since the _usern value in session is poped in the first visit.
  • If you want to show the flash messages, you have to render it in the template (get_flashed_messages) and return the template in your view function, but your hello view doesn't return the hello.html template, so any messages you flashed then redirect to this hello view will not display. However, the flash messages will store in session (cookie), once you visit /login (that render hello.html), all the messages you flashed will show up altogether.

Please use Stack Overflow for the problem related to your code next time, this issue tracker is for Flask itself.

greyli avatar Jun 16 '20 14:06 greyli