test_flush.py
from flask import Flask, flash, redirect, render_template, request, url_for
from flask_debugtoolbar import DebugToolbarExtension
debugToolbar = DebugToolbarExtension()
app = Flask(__name__, template_folder='../templates')
app.secret_key = 'some_secret'
@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(message='You were successfully logged in.', category='error')
return redirect(url_for('index'))
return render_template('login.html', error=error)
if __name__ == "__main__":
app.debug = True
debugToolbar.init_app(app)
app.run()
index.html
{% extends "layout.html" %}
{% block body %}
<h1>Overview</h1>
<p>Do you want to <a href="{{ url_for('login') }}">log in?</a>
{% endblock %}
layout.html
<!doctype html>
<title>My Application</title>
{#{% with errors = get_flashed_messages(category_filter=["error"]) %}#}
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul class=flashes>
{% for category, message in messages %}
<li>{{ category }}:{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block body %}{% endblock %}
{% extends "layout.html" %}
{% block body %}
<h1>Login</h1>
{% if error %}
<p class=error><strong>Error:</strong> {{ error }}
{% endif %}
<form action="" 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></p>
</form>
{% endblock %}