Flask 消息提示与异常处理
1. 消息提示
flask 中提供了消息闪现机制,方便我们消息提示,所使用的模块是 flash
模块。在我们使用 flash
时,我们需要调用 app.secret_key
字段,该字段会对消息进行加密。具体代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-from flask import Flask, render_template, flashapp = Flask(__name__)
app.secret_key = '123456'@app.route('/')
def hello_world():flash('hello flash')return render_template("index.html")if __name__ == "__main__":app.run()
之后,我们编写 index.html 页面。在该页面中,我们使用 get_flashed_messages()
函数来得到flash
中的内容,但注意,这个返回的是一个数组,因为我们只有一条消息,所以我们只取第一个元素,具体代码如下:
<!DOCTYPE html>
<html>
<head><title>Test</title>
</head>
<body>
<h1>Hello</h1><h2>{{ get_flashed_messages()[0] }}</h2>
</body>
</html>
接下来,我们来模拟网页用户登录时的一些消息提示,如果你还不了解如何处理表单,可以查看这篇博客。
首先,我们先查看一下我们文件的结构树,如下:
192:test ming$ tree
.
├── app.py
├── static
└── templates├── index.html└── login.html2 directories, 3 files
首先,我们来编写 login.html 文件,如下:
<!DOCTYPE html>
<html>
<head><title>Test</title>
</head>
<body><div align="center"><h1>User Management</h1>{% if get_flashed_messages() %}{{ get_flashed_messages()[0] }}{% endif %}<form action="/check" method="post">Username: {{ form.username }} <br />Password: {{ form.password }} <br /><input type="submit" value="Submit" /><input type="reset" value="Reset" /></form></div>
</body>
</html>
然后,我们来编写 app.py 文件,如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-from flask import Flask, render_template, flash
from wtforms import Form, TextField, PasswordField, validators
from flask import request
from flask import url_for, redirectapp = Flask(__name__)
app.secret_key = '123456'class LoginForm(Form):username = TextField("username", [validators.Required()])password = PasswordField("password", [validators.Required()])@app.route('/')
def index():return render_template('index.html')@app.route('/login')
def login():myForm = LoginForm(request.form)return render_template("login.html", form = myForm)@app.route('/check', methods=["POST"])
def check():myForm = LoginForm(request.form)username = myForm.username.datapassword = myForm.password.dataif not username:flash('please input username')return redirect(url_for('login'))if not password:flash('please input password')return redirect(url_for('login'))if username == 'admin' and password == 'admin':flash('login success')return redirect(url_for('index'))else:flash('username or password is wrong')return redirect(url_for('login'))if __name__ == "__main__":app.run()
最后,为了查看效果,我们来编写一个简单的 index.html 文件,如下:
<!DOCTYPE html>
<html>
<head><title>Test</title>
</head>
<body>{% if get_flashed_messages()[0] == 'login success' %}{{ get_flashed_messages()[0] }}{% endif %}<h1> 这是主页 </h1>
</body>
</html>
至此,你应该已经学会了一些基础的消息提示操作吧。
2. 异常处理
接下来,我们来学习 flask 中的异常处理。
当我们访问一个网站的时候,有时候我们会输入一个 URL 不存在的网站,这时候如果跳出来一个 404 的界面,那么用户体验是非常不好的。而这一节就是来处于 404 界面的问题。
那么,在 flask 中提供了一个这样的装饰器 errorhandler
,专门来处理一些http错误。比如,我们在 app.py 文件中加入下列代码:
@app.errorhandler(404)
def not_found(e):return render_template('404.html')
之后运行这个程序,在浏览器中随便输入一个网站,可以得到如下界面:
![](https://static.oschina.net/uploads/img/201709/10012429_T2UK.png)
这样,就能比较友好的处理 404 错误。
接下来,举一个比较实用的例子。比如,我们需要判断用户是否存在。在 app.py 代码中,我们可以加入如下代码:
@app.errorhandler(404)
def not_found(e):return render_template('404.html')@app.route('/users/<user_id>')
def users(user_id):if int(user_id) == 1:return render_template('users.html', user = user_id)else:abort(404)
然后编写 users.html 页面,如下:
<!DOCTYPE html>
<html>
<head><title></title>
</head>
<body>
User ID: {{ user}}
</body>
</html>
最后,你运行该程序之后,当你访问 http://localhost:5000/users/1
时,可以得到如下正确访问页面:
![](https://static.oschina.net/uploads/img/201709/10012433_9s9c.png)
但是当你访问 http://localhost:5000/users/2
时,你将得到 404 页面,如下:
![](https://static.oschina.net/uploads/img/201709/10012435_tpQW.png)
至此,我们学习完了异常处理。
转载于:https://my.oschina.net/u/3579120/blog/1533455
Flask 消息提示与异常处理相关推荐
- Flask消息闪现及日志记录
消息闪现 Flask 提供了一个非常简单的方法来使用闪现系统向用户反馈信息.闪现系统使得在一个请求结束的时候记录一个信息,然后在且仅仅在下一个请求中访问这个数据.Flask消息闪现可以给用户更好的体验 ...
- QGC注释消息提示框
消息提示框:有时显示时覆盖想要看的界面,可注释!
- Silverlight+WCF 实战-网络象棋最终篇之解决重复的消息提示(八)
前言: 最近有网友经常会问,在跟着做象棋对战的通讯中,在重复退出进入的时候,消息会重复出现,本节就这问题进行解说与优化. 一:分析问题产生的原因? 1:首先看App.xaml,里面定义了一个全局客户端 ...
- ymPrompt.js消息提示组件
详细说明: http://www.ajaxbbs.net/test/ymPrompt4.0/demo.html 1.在页面中引入ymPrompt.js.如:<script type=" ...
- 【WPF】屏幕右下角消息提示框
WPF做一个仿QQ的右下角消息提示窗,网上找到几个Demo后,选了一个比较好用的. 博客 http://blog.csdn.net/huangli321456/article/details/5052 ...
- 030_Message消息提示
1. Message消息提示 1.1. Message消息提示常用于主动操作后的反馈提示.与Notification的区别是后者更多用于系统级通知的被动提醒. 1.2. Options 参数 说明 类 ...
- Qt QWidget实现消息提示控件TipsWidget
前言 用Qt实现一个消息提示控件,控件宽度会根据显示的内容多少来动态伸展,控件显示三秒钟过后会自动渐变透明度然后最终消失,这有点类似于Android的Toast控件,都是用于消息短暂提示. 源码 头文 ...
- Message 消息提示
常用于主动操作后的反馈提示.与 Notification 的区别是后者更多用于系统级通知的被动提醒. 基础用法 从顶部出现,3 秒后自动消失. Message 在配置上与 Notification 非 ...
- Android安卓程序消息提示和按钮响应事件
首先在界面的XML里添加按钮响应函数 android:onClick="OnMyClick" <Buttonandroid:id="@+id/button1&quo ...
最新文章
- 1047.删除字符串中的相邻重复项
- 关于mysql中truncate
- Apache Beam欲通过uber api获取大数据
- 推荐阅读《赢在下班后》
- Python(2):基本数据类型
- html app从上向下弹框,移动端从底部向上过渡弹出弹框
- IOS基础之使用UICollectionView纯代码创建
- 余弦相似度和欧氏距离_欧氏距离和余弦相似度
- 大数据技术周报第 003 期
- 极域电子教室破解还原卡
- Java 后端开发必读的 6 本书!
- multisim仪表运放_Multisim仿真---三运放仪表放大器
- 服务器上删掉的数据如何找回,在服务器数据丢失情况下如何恢复数据
- 安卓手机误删文件恢复
- Google Test - Google Testing and Mocking Framework
- python之路_面向对象
- 线性代数(二十四) : 行列式的展开式—拉普拉斯公式
- Java查询快递物流信息写法【免费】
- oracle的rowid和rownum,【oracle rowid与rownum的使用与区别 】
- spring cloud eureka无法加载样式wro.css和脚本wro.js