Flask消息闪现
Flask消息闪现
一个好的应用和用户界面都需要良好的反馈。如果用户得不到足够的反馈,那么应用最终会被用户唾弃。
Flask 的闪现系统提供了一个良好的反馈方式。
闪现系统的基本工作方式是:
- 在且只在下一个请求中访问上一个请求结束时记录的消息。
- 一般我们 结合布局模板来使用闪现系统。
- 注意,浏览器会限制 cookie 的大小,有时候网络服 务器也会。这样如果消息比会话 cookie 大的话,那么会导致消息闪现静默失败。
简单的例子
以下是一个完整的示例:
from flask import Flask, flash, redirect, render_template, \
request, url_for
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
@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)
上面py文件比如保存为flashtest.py
以下是实现闪现的 layout.html 模板:
注,html模板默认放在项目的templates目录下。
<!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 %}
以下是继承自 layout.html 的 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 的 login.html 模板:
{% extends "layout.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 %}
运行应用
>set FLASK_APP=flashtest.py
>python -m flask run
访问默认的127.0.0.1:5000可见闪现效果:

闪现消息的类别
闪现消息还可以指定类别,如果没有指定,那么缺省的类别为 'message' 。不同的 类别可以给用户提供更好的反馈。例如错误消息可以使用红色背景。(样式要自己根据class=类别额外去写好css)
使用 flash() 函数可以指定消息的类别:
flash(u'Invalid password provided', 'error')
注: 这一行是添加在 error= 'Invalid credentials' 这一行之后:
@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'
flash(u'Invalid password provided', category='error')
else:
flash('You were successfully logged in')
return redirect(url_for('index'))
return render_template('login.html',error=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>{{ category }}:</strong> 。
<!DOCTYPE html>
<title>My Application</title>
{% with messages = get_flashed_messages(with_categories=True) %}
{% if messages %}
<ul class=flashes>
{% for category, message in messages %}
<li class="{{ category }}"><strong>{{ category }}:</strong>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block body %}{% endblock %}
注:虽然可以拿到类别,但是要依据类别来写li标签的样式,让错误信息显示是红色背景还要自己额外去写好样式哦。
过滤闪现消息
你可以视情况通过传递一个类别列表来过滤 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 %}
flask.flash() 和 get_flashed_messages() 官网说明如下:
Message Flashing
flask.flash(message, category='message')
Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call get_flashed_messages().
Parameters:
message – the message to be flashed.
category – the category for the message.
The following values are recommended:
'message' for any kind of message,
'error' for errors,
'info' for information messages and 'warning' for warnings.
However any kind of string can be used as category.
flask.get_flashed_messages(with_categories=False, category_filter=[])
Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when with_categories is set to True, the return value will be a list of tuples in the form (category, message) instead. Filter the flashed messages to one or more categories by providing those categories in category_filter. This allows rendering categories in separate html blocks. The with_categories and category_filter arguments are distinct: with_categories controls whether categories are returned with message text (True gives a tuple, where False gives just the message text). category_filter filters the messages down to only those matching the provided categories.
See 消息闪现 for examples.
Parameters:
with_categories – set to True to also receive categories.
category_filter – whitelist of categories to limit return values
从官网里可以看出,flash() 函数:
第一个参数是你将要放进去的字符串消息,
第二个默认参数category,代表消息的类别,默认为message(消息,普通)。
而get_flashed_messages() 两个默认参数,第一个是类别控制开关,默认是False。
- 类别控制是否带消息文本返回类别:
- True给出一个tuple,元祖中给出两个值,分别是消息文本和类别;
- False只给出消息文本,不返回类别。
文:铁乐与猫
2018-9-6
参考
Flask消息闪现的更多相关文章
- 19,flask消息闪现-flash
Flash消息 请求完成后给用户的提醒消息,flask的核心特性, flash函数实现效果 视图函数中调用flash()方法 html中要使用get_flashed_messages() 后端代码: ...
- Flask -- 消息闪现、错误处理
flash 可以在任何需要的地方添加,类似于print from flask import flash @app.route('/') def index(): flash('You are in h ...
- Flask form前后端交互消息闪现
模拟场景如果当用户注册时输入错误而由于form表单是同步提的交跳转到另一个网页时提示注册失败这时用户还需返回注册页面重新填写大大降低了客户体验,消息闪现能伪装成异步(实际还是同步)就是自己提交给自己然 ...
- python web开发-flask中消息闪现flash的应用
Flash中的消息闪现,在官方的解释是用来给用户做出反馈.不过实际上这个功能只是一个记录消息的方法,在某一个请求中记录消息,在下一个请求中获取消息,然后做相应的处理,也就是说flask只存在于两个相邻 ...
- flask模板应用-消息闪现(flash())
消息闪现 flask提供了一个非常有用的flash()函数,它可以用来“闪现”需要提示给用户的消息,比如当用户登录成功后显示“欢迎回来!”.在视图函数调用flash()函数,传入消息内容,flash( ...
- Flask框架flash消息闪现学习与优化符合闪现之名
Flask的flash 第一次知道Flask有flash这个功能时,听这名字就觉得高端,消息闪现-是跳刀blink闪烁躲技能的top10操作吗?可结果让我好失望,哪里有什么闪现的效果,不过是平常的消息 ...
- python tornado 中使用 flash消息闪现
1.html 中引入文件 {% block head %} <link href="/static/common/sweetalert/sweetalert.css" rel ...
- Flask Flash闪现
Flash介绍以及工作方式 flash中添加消息 取出flash中的消息 Flash介绍以及工作方式 - 介绍: flash :闪现 一个好的应用和用户界面都需要良好的反馈. 如果用户得不到足够的反馈 ...
- Flask的闪现(message) 请求扩展 中间件 蓝图
补充:一个编程思路 需求:做一些邮件短信微信的消息通知,比如账单告警之类的:比如数据库操作,数据库种类繁多:缓存的选择比如redis/memcache,诸如此类需要进行选择配置,如果我们单纯的用函数去 ...
随机推荐
- 《Kubernetes权威指南》——Kubelet运行机制与安全机制
1 Kubelet运行机制 Kubenetes集群中的每个Node节点都会启动一个Kubelet服务进程用于处理Master下发到该节点的任务,管理Pod及其中的容器 Kubelet进程在API Se ...
- Linux_CentOS-服务器搭建 <五> 补充
O:文件的编码格式 1.文件转码问题 Windows中默认的文件格式是GBK(gb2312),而Linux一般都是UTF-8. 那么先说,如何查看吧.这时候强大的vi说,I can do that.( ...
- java高级工程师开放面试题集<一>
临近年关,不少人蠢蠢欲动,有童鞋问我java后端面试会面试什么? 作为一个java后端老鸟,跌打滚爬多次被面试和面试别人,总结了一些经验,希望对大家有所帮助. 特别说明,仅仅针对工作两年以上的java ...
- 3分钟看完Java 8——史上最强Java 8新特性总结之第一篇 函数式编程基础
目录 · 行为参数化 · Lambda表达式 · 概况 · 函数式接口 · 类型推断 · 使用外层变量 · 方法引用 · 复合Lambda表达式 行为参数化 1. 理解函数式编程要先理解行为参数化. ...
- [JZOJ5837] Omeed
Description Solution 有两种做法 一种是线段树维护一次方程系数,一种是线段树维护矩阵 准备都写一写 维护系数 首先把式子推出来 \[CS=B\times \sum\limits_{ ...
- Ocelot中文文档-Configuration
配置 一个关于Ocelot配置例子在这里.配置有两个部分.一个数组类型的ReRoutes和一个全局配置.ReRoutes是个对象,告诉Ocelot怎么去处理一个上游请求.全局配置有点繁琐(is a h ...
- Xshell配置密钥公钥(Public key)与私钥(Private Key)登录
ssh登录提供两种认证方式:口令(密码)认证方式和密钥认证方式.其中口令(密码)认证方式是我们最常用的一种,这里介绍密钥认证方式登录到linux/unix的方法. 使用密钥登录分为3步:1.生成密钥( ...
- 【Spring】10、Spring中用@Component、@Repository、@Service和 @Controller等标注的默认Bean名称会是小写开头的非限定类名
@Service用于标注业务层组件(我们通常定义的service层就用这个) @Controller用于标注控制层组件(如struts中的action) @Repository用于标注数据访问组件,即 ...
- Flask 中的 特殊装饰器before_request/after_request
before_request :在请求收到之前绑定一个函数做一些事情. after_request: 每一个请求之后绑定一个函数,如果请求没有异常. teardown_request: 每一个请求之后 ...
- Csharp:Paging Sorting Searching In ASP.NET MVC 5
http://www.c-sharpcorner.com/UploadFile/0c1bb2/sorting-paging-searching-in-Asp-Net-mvc-5/ https://dz ...