Flask 提供了一個非常簡單的方法來使用閃現(xiàn)系統(tǒng)向用戶反饋信息。閃現(xiàn)系統(tǒng)使得在一個請求結(jié)束的時候記錄一個信息,并且在下次(且僅在下一次中)請求時訪問它,這通常與布局模板結(jié)合使用以公開信息。
在 Flask Web 應(yīng)用程序中生成這樣的信息性消息很容易。Flask 框架的閃現(xiàn)系統(tǒng)可以在一個視圖中創(chuàng)建消息,并在名為 next 的視圖函數(shù)中呈現(xiàn)它。
Flask 模塊包含 flash() 方法。它將消息傳遞給下一個請求,該請求通常是一個模板。
flash(message, category)
其中,
message 參數(shù)是要閃現(xiàn)的實際消息。
category 參數(shù)是可選的。它可以是“error”,“info”或“warning”。
為了從會話中刪除消息,模板調(diào)用 get_flashed_messages()。
get_flashed_messages(with_categories, category_filter)
兩個參數(shù)都是可選的。如果接收到的消息具有類別,則第一個參數(shù)是元組。第二個參數(shù)僅用于顯示特定消息。
以下閃現(xiàn)在模板中接收消息。
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
{% endwith %}
讓我們看一個簡單的例子,演示Flask中的閃現(xiàn)機制。在以下代碼中,'/' URL 顯示登錄頁面的鏈接,沒有消息閃現(xiàn)。
@app.route('/')
def index():
return render_template('index.html')
該鏈接會將用戶引導(dǎo)到'/login' URL,該 URL 顯示登錄表單。提交時,login() 視圖函數(shù)驗證用戶名和密碼,并相應(yīng)閃現(xiàn) 'success' 消息或創(chuàng)建 'error' 變量。
@app.route('/login', methods = ['GET', 'POST'])
def login():
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('index'))
return render_template('login.html', error = error)
如果出現(xiàn)錯誤,則會重新顯示登錄模板,并顯示錯誤消息。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form method = "post" action = "http://localhost:5000/login">
<table>
<tr>
<td>Username</td>
<td><input type = 'username' 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>
另一方面,如果登錄成功,則會在索引模板上刷新成功消息。
<!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('login') }}">login</a>
</body>
</html>
下面給出了 Flask 消息閃現(xiàn)示例的完整代碼:
from flask import Flask, flash, redirect, render_template, request, url_for
app = Flask(__name__)
app.secret_key = 'random string'
@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'] != 'admin':
error = 'Invalid username or password. Please try again!'
else:
flash('You were successfully logged in')
return redirect(url_for('index'))
return render_template('login.html', error = error)
if __name__ == '__main__':
app.run(debug=True)
執(zhí)行上述代碼后,您將看到如下所示的界面。
當(dāng)您點擊鏈接,您將被定向到登錄頁面。
輸入用戶名和密碼。
點擊登錄。將顯示一條消息“您已成功登錄”。
更多建議: