外观
消息闪现
如用户在登录时,用户名输入错误或密码错误时,页面的特定位置会显示错误信息。Flask提供了一个flash()函数,它可以闪现给用户需要的信息。
flash()函数的语法如下:
flash(massage, category)参数message代表消息内容,category代表消息类型,用于对不同的消息内容分类处理。
通常在视图函数中使用flash()函数,传入消息内容即可闪现一条消息。注意,闪现不是在用户窗口弹出一条消息。实际上,通过flash()函数发送的消息会存储在Session中,需要在模板中使用全局函数get_flashed_messages()获取消息列表,并将其显示出来。
通过flash()函数发送的消息会存储在Session中,因此需要将程序设置一个密钥。
如我们通过以下例子将用户登录成功或失败的消息闪现出来。
run.py
from flask import Flask, render_template, flash, request, url_for, redirect
app = Flask(__name__)
app.config['SECRET_KEY'] = 'qi1'
@app.route('/', methods=['GET','POST'])
def index():
if request.method == 'POST':
if request.form['user'] == 'qi' and request.form['password'] == '123456':
flash('登录成功', 'success')
else:
flash('登录失败', 'error')
return render_template('index.html')
if __name__ == '__main__':
app.run()run.py中,检测若方法为POST则验证表单中的数据,若数据错误则闪现错误的信息,若数据正确则闪现正确的信息,并设定它们对应的类型。
index.html
<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>登录</title>
<style>
.success {
color: black;
}
.login {
color: red;
}
ul, li{
margin: 0;
}
</style>
</head>
<body>
<form action="" method="post">
<label for="user">账号</label><input type="text" id="user" name="user"><br/>
<label for="password">密码</label><input type="text" id="password" name="password"><br/>
{% with messages = get_flashed_messages(with_categories=True) %}
<ul>
{% if messages %}
{% for message, category in messages %}
<li class={{ category }}>{{ message }}</li>
{% endfor %}
{% endif %}
</ul>
{% endwith %}
<input type="submit" value="登录">
</form>
</body>
</html>在index.html中,表单是必不可少的。在显示结果方面, 先使用with语句与get_flashed_messages(with_categories=True)获取所有闪现的消息,加with是限定其作用域。然后它会返回一个列表。若这个列表中存在消息,就遍历这个消息,并将它们输出。