Flask 消息闪现
一个好的基于GUI的应用程序会向用户提供有关交互的反馈。例如,桌面应用程序使用对话框或消息框,JavaScript使用警报用于类似目的。
在Flask Web应用程序中生成这样的信息性消息很容易。Flask框架的闪现系统可以在一个视图中创建消息,并在名为next的视图函数中呈现它。
Flask模块包含flash()方法。它将消息传递给下一个请求,该请求通常是一个模板。
flash(message, category)
其中,
-
message参数是要闪现的实际消息。
-
category参数是可选的。它可以是“error”,“info”或“warning”。
为了从会话中删除消息,模板调用get_flashed_messages()。
get_flashed_messages(with_categories, category_filter)
两个参数都是可选的。如果接收到的消息具有类别,则第一个参数是元组。第二个参数仅用于显示特定消息。
index2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<p>{{ message }}</p>
{% endfor %}
{% endif %}
{% endwith %}
<h3>Welcome!</h3>
<a href = "{{ url_for('login2') }}">login</a>
</body>
</html>
login2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form method = "post" action = "http://localhost:5000/login2">
<table>
<tr>
<td>Username</td>
<td><input type = 'text' name = 'username'></td>
</tr>
<tr>
<td>Password</td>
<td><input type = 'password' name = 'password'></td>
</tr>
<tr>
<td><input type = "submit" value = "Submit"></td>
</tr>
</table>
</form>
{% if error %}
<p><strong>Error</strong>: {{ error }}</p>
{% endif %}
</body>
</html>
上面的html文件都是在templates文件夹中的
flash.py
from flask import Flask, flash, redirect, render_template, request, url_for
app = Flask(__name__)
app.secret_key = 'random string'
@app.route('/')
def index2():
return render_template('index2.html')
@app.route('/login2', methods = ['GET', 'POST'])
def login2():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or \
request.form['password'] != 'admin':
error = 'Invalid username or password. Please try again!'
else:
flash('You were successfully logged in')
return redirect(url_for('index2'))
return render_template('login2.html', error = error) #这里其实相当于重新加载了,所以才会判断对错
if __name__ == "__main__":
app.run(debug = True)