好的应用和用户界面的重点是回馈,但是如果用户没有得到足够的反馈,他们可能最终会对我们的应用产生不好的评价。Flask 提供了一个非常简单的方法来使用闪现系统向用户反馈信息,那就是闪现系统。它使得在一个请求结束的时候记录一个信息,然后在且仅仅在下一个请求中访问这个数据,并且这个功能通常配合一个布局模板实现。这个有点类似与PHP的laravel框架中的session_flash()函数的功能。
我们来看一个完成的例子,首先是逻辑代码:
from flask import Flask, flash, redirect, render_template, \ request, url_for app = Flask(__name__) 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('You were successfully logged in') return redirect(url_for('index')) return render_template('login.html', error=error) if __name__ == "__main__": app.run()
然后我们来看模板文件,首先是公共模板layout.html:
<!doctype html> <title>My Application</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 %}
完事就是index.html 模板:
{% extends "layout.html" %} {% block body %} <h1>Overview</h1> <p>Do you want to <a href="{{ url_for('login') }}">log in?</a> {% 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> </form> {% endblock %}
把上述的代码放到不同的文件中,运行python的py文件,就可以在浏览器中看到想要的效果了。
完事,在flask的0.3 新版提供了一个新的名叫分类闪现的功能。并且未指定分类时默认的分类为 'message'。我们可以使用分类来提供给用户更好的反馈,例如,错误信息应该被显示为红色北京。
我们如果要使用一个自定义的分类,只要使用 flash() 函数的第二个参数:
flash(u'Invalid password provided', 'error')
在模板中,我们接下来可以调用 get_flashed_messages() 函数来返回这个分类,在下面的情景中,循环看起来将会有一点点不一样 :
% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} <ul class=flashes> {% for category, message in messages %} <li class="{{ category }}">{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %}
这仅仅是一个渲染闪现信息的例子,我们也可以使用分类来加入一个诸如 <strong>Error:</strong> 的前缀给信息。
完事在flask0.9 新版中,又添加了一个过滤闪现消息的功能。我们可以可选的将一个分类的列表传入到 get_flashed_messages() 中, 然后以过滤函数返回的结果,在我们希望将每个分类渲染到独立的块中的时候,这会非常有用:
{% with errors = get_flashed_messages(category_filter=["error"]) %} {% if errors %} <div class="alert-message block-message error"> <a class="close" href="#">×</a> <ul> {%- for msg in errors %} <li>{{ msg }}</li> {% endfor -%} </ul> </div> {% endif %} {% endwith %}
好啦,本次记录就到这里了。
如果感觉不错的话,请多多点赞支持哦。。。