flask flash消息闪现

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 %}


login.html

{% 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 %}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值