Ruby on Rails has a way that you can set a message, like flash[:notice]
and flash[:error
, that the user will see at the next opportunity. It’s especially useful for things like notifying the user of failure to log in, etc., when they are redirected (e.g. back to a sign-in page).
Is there a canonical or common way to achieve this on Google App Engine (Python API)? (Assume Django is not being used.)
Yes, look at this function
get_flashes(key='_flash')[source]
in this object:class webapp2_extras.sessions.SessionDict(container, data=None, new=False)[source]
What do you think about extending a template and setting the "flash" parameter to the template?
for example, base template :
now at every template
your handler should pass flash param to the template, it will be used at the base template.
Webapp framework, the simple web application framework that ships with GAE, does not provide something like that.
One cool framework built specifically for Google App Engine that offers Flash messages is Tipfy.
Have a look to tipfy.ext.session module:
Well, webapp2 does have:
and:
That stores your messages and deletes them when read. To show them to the user, you just need to set a variable in your base request handlers
render_template
method. Something like this:And in your template, use the 'flashes' variable to display your messages however you like.
Docs here: http://code.google.com/p/webapp-improved/source/browse/webapp2_extras/sessions.py?r=9c1ec933be7c3d8c09c9bf801ebffe2deeb922e0#127
Live example over here: https://simpleauth.appspot.com/
and the example's source: http://code.google.com/p/gae-simpleauth/source/browse/example/handlers.py
By the way, great work with simpleauth Alex!
I like llazzaro's advice regarding templates.
The other half to the story is being able to maintain the flash message between requests.
If you are dealing with sessions, stick the message in the session.
If you don't have session support, you'll have to create use a cookie.
Cookie caveats:
Regardless, when you display flash messages, immediately clear the message from the session or cookie.