flask Flash消息

1.在路由中添加flash消息

from flask import Flask, render_template, session, redirect, url_for, flash
@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        old_name = session.get('name')
        if old_name is not None and old_name != form.name.data:
            flash('Looks like you have changed your name!') # 返回flash
        session['name'] = form.name.data
        return redirect(url_for('index'))
    return render_template('index.html',
form = form, name = session.get('name'))

2.在模板中渲染flash

{% for message in get_flashed_messages() %}#在请求中每次调用flash()都会返回一个消息,他们会排队等待显示
{{ message }}
{% endfor %}

你可能感兴趣的:(flask)