Python Flask-Simple Flashing

Flask Message Flashing

Good applications and user interfaces are all about feedback. Flask provides a simple way to give feedback to a user with the flashing system. It basically makes it possible to record a message at the end of a request and access it next request and only the next request. This is usually combined with a layout template that does this. Browsers and sometimes web servers enforce a limit on cookie sizes. Flashing messages mean that are too large for session cookies that cause message flashing to fail silently.

Simple Flashing
from flask import Flask, flash, redirect, render_template, \
     request, url_for
app = Flask(__name__)
app.secret_key = b'_8#y4L"F4Q8z\n\sec]/'
@app.route('/')
def index():
    return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != 'admin' or \
                request.form['password'] != 'secret':
            error = 'Invalid credentials'
        else:
            flash('You were successfully logged in')
            return redirect(url_for('index'))
    return render_template('login.html', error=error)
And here is the flash.html template which does the magic:
<!doctype html>
<title>Message Flashing</title>
{% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
    {% for message in messages %}
      <li>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}
{% block body %}{% endblock %}
Here is the index.html template which inherits from flash.html:
{% extends "flash.html" %}
{% block body %}
  <h1>Overview</h1>
  <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>
{% endblock %}
And here is the login.html template which also inherits from flash.html:
{% extends "flash.html" %}
{% block body %}
  <h1>Login</h1>
  {% if error %}
    <p class=error><strong>Error:</strong> {{ error }}
  {% endif %}
  <form method=post>
    <dl>
      <dt>Username:
      <dd><input type=text name=username value="{{
          request.form.username }}">
      <dt>Password:
      <dd><input type=password name=password>
    </dl>
    <p><input type=submit value=Login>
  </form>
{% endblock %}