librelist archives

« back to archive

flash message in a function decorator.

flash message in a function decorator.

From:
Joe Martin
Date:
2012-03-31 @ 11:51
Hello all,

I tried flask-login a while, but it didn't exactly meet my requirements.
However, it has a nice decorator called login_required. Flask documentation
also describes similar decorator. So, I used the one in the doc, and
added a flash message:

from functools import wraps
from flask import g, flash, redirect, url_for

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if g.user_id is None:
            flash("You must login.", 'error')
            return redirect(url_for("main.login"))
        return f(*args, **kwargs)
    return decorated_function

I have the following 2 urls:
1) /login
2) /client - which requires login (decorated with @login_required)

If I access "/client", without first logging in, then page is redirected to
"/login",
as expected. The problem is flash message is lost. Using Fiddler2,
I compared this to the case when flask-login was used:
1) in case when flask-login extension is used,
  '/client' response header has "Set-Cookie:
session="txbmjOxN4xRo4aT+ewaviQvYeDA=?_flashes=KGxwMQooU..."
 '/login' header is the same as above.
2) In my own decorator case, '/client' response header has similar things
as above, but
'/login' header has different session id and there's no _flashes.

So, can you explain me what am I missing? Thank you.