Message Flashing

Good applications and user interfaces are all about feedback. If the userdoes not get enough feedback they will probably end up hating theapplication. Flask provides a really simple way to give feedback to auser with the flashing system. The flashing system basically makes itpossible to record a message at the end of a request and access it nextrequest and only next request. This is usually combined with a layouttemplate that does this. Note that browsers and sometimes web servers enforcea limit on cookie sizes. This means that flashing messages that are toolarge for session cookies causes message flashing to fail silently.

Simple Flashing

So here is a full example:

fromflaskimportFlask,flash,redirect,render_template, \request,url_forapp=Flask(__name__)app.secret_key=b'_5#y2L"F4Q8z\n\xec]/'@app.route('/')defindex():returnrender_template('index.html')@app.route('/login',methods=['GET','POST'])deflogin():error=Noneifrequest.method=='POST':ifrequest.form['username']!='admin'or \request.form['password']!='secret':error='Invalid credentials'else:flash('You were successfully logged in')returnredirect(url_for('index'))returnrender_template('login.html',error=error)

And here is thelayout.html template which does the magic:

<!doctype html><title>My Application</title>{%withmessages=get_flashed_messages()%}{%ifmessages%}<ulclass=flashes>{%formessageinmessages%}<li>{{message}}</li>{%endfor%}</ul>{%endif%}{%endwith%}{%blockbody%}{%endblock%}

Here is theindex.html template which inherits fromlayout.html:

{%extends"layout.html"%}{%blockbody%}<h1>Overview</h1><p>Do you want to<ahref="{{url_for('login')}}">log in?</a>{%endblock%}

And here is thelogin.html template which also inherits fromlayout.html:

{%extends"layout.html"%}{%blockbody%}<h1>Login</h1>{%iferror%}<pclass=error><strong>Error:</strong>{{error}}{%endif%}<formmethod=post><dl><dt>Username:<dd><inputtype=textname=usernamevalue="{{request.form.username}}"><dt>Password:<dd><inputtype=passwordname=password></dl><p><inputtype=submitvalue=Login></form>{%endblock%}

Flashing With Categories

Changelog

Added in version 0.3.

It is also possible to provide categories when flashing a message. Thedefault category if nothing is provided is'message'. Alternativecategories can be used to give the user better feedback. For exampleerror messages could be displayed with a red background.

To flash a message with a different category, just use the second argumentto theflash() function:

flash('Invalid password provided','error')

Inside the template you then have to tell theget_flashed_messages() function to also return thecategories. The loop looks slightly different in that situation then:

{%withmessages=get_flashed_messages(with_categories=true)%}{%ifmessages%}<ulclass=flashes>{%forcategory,messageinmessages%}<liclass="{{category}}">{{message}}</li>{%endfor%}</ul>{%endif%}{%endwith%}

This is just one example of how to render these flashed messages. Onemight also use the category to add a prefix such as<strong>Error:</strong> to the message.

Filtering Flash Messages

Changelog

Added in version 0.9.

Optionally you can pass a list of categories which filters the results ofget_flashed_messages(). This is useful if you wish torender each category in a separate block.

{%witherrors=get_flashed_messages(category_filter=["error"])%}{%iferrors%}<divclass="alert-message block-message error"><aclass="close"href="#">×</a><ul>{%-formsginerrors%}<li>{{msg}}</li>{%endfor -%}</ul></div>{%endif%}{%endwith%}