个性化阅读
专注于IT技术分析

Python Flask使用flash()方法

点击下载

在Web应用程序中, 在某些情况下, 开发人员可能需要刷新消息以向用户提供有关应用程序在不同情况下的行为的反馈。

Flask以相同的方式提供flash()方法, 像JavaScript这样的客户端脚本语言使用警报或python GUI框架Tkinter使用对话框或消息框。

flash()方法用于在Python Flask中生成信息性消息。它在一个视图中创建一条消息, 并将其呈现给名为next的模板视图函数。

换句话说, flask模块的flash()方法将消息传递给下一个请求, 即HTML模板。下面给出了使用flash()方法的语法。

flash(message, category)

它接受以下参数。

  • 消息:这是要刷新给用户的消息。
  • 类别:这是一个可选参数。可能代表任何错误, 信息或警告。

消息是使用flask模块的flash()方法在flask脚本中生成的。这些消息需要从会话中提取到模板中。为此, 在HTML模板中调用方法get_flashed_messages()。

下面给出了使用此方法的语法。

get_flashed_messages(with_categories, category_filter)

它接受以下参数。

  • with_categories:此参数是可选的, 如果消息具有类别, 则使用此参数。
  • category_filter:此参数也是可选的。仅显示指定的消息很有用。

例子

该示例包含用于服务器和客户端脚本的Flask和HTML脚本。

python脚本刷新消息, 然后根据用户的成功登录和失败登录将用户重定向到其他HTML脚本。

flashing.py

from flask import *
app = Flask(__name__)
app.secret_key = "abc"

@app.route('/index')
def home():
	return render_template("index.html")

@app.route('/login', methods = ["GET", "POST"])
def login():
	error = None;
	if request.method == "POST":
		if request.form['pass'] != 'jtp':
			error = "invalid password"
		else:
			flash("you are successfuly logged in")
			return redirect(url_for('home'))
	return render_template('login.html', error=error)

	
if __name__ == '__main__':
	app.run(debug = True)

index.html

<html>
<head>
<title>home</title>
</head>
<body>
	{% with messages = get_flashed_messages() %}
         {% if messages %}
               {% for message in messages %}
               		<p>{{ message }}</p>
               {% endfor %}
         {% endif %}
      {% endwith %}
<h3>Welcome to the website</h3>
<a href = "{{ url_for('login') }}">login</a>
</body>
</html>

login.html

<html>
<head>
	<title>login</title>
</head>
<body>
	{% if error %}
		<p><strong>Error</strong>: {{error}}</p>
	{% endif %}

	<form method = "post" action = "/login">
		<table>
			<tr><td>Email</td><td><input type = 'email' name = 'email'></td></tr>
			<tr><td>Password</td><td><input type = 'password' name = 'pass'></td></tr>
		    <tr><td><input type = "submit" value = "Submit"></td></tr>
		</table>
	</form>
</body>
</html>

URL / index显示以下模板(index.html), 其中包含用于闪烁消息的代码(如果有)。链接登录将用户重定向到URL / login。

Python Flask使用flash()方法

下页显示了login.html模板, 该模板提示用户输入电子邮件ID和密码。在此, 如果用户输入除” jtp”以外的任何随机密码, 则无法登录该应用程序。

Python Flask使用flash()方法

以下网址说明了用户输入错误密码的第一种情况。脚本login.py生成一条错误消息, 显示为”无效密码”, 并将用户重定向到此页面本身。

Python Flask使用flash()方法

以下URL说明了第二种情况, 用户输入了正确的密码” jtp”, 因此脚本flashing.py闪烁了成功消息, 并将用户重定向到URL http:localhost:5000 / index。

Python Flask使用flash()方法

赞(0)
未经允许不得转载:srcmini » Python Flask使用flash()方法

评论 抢沙发

评论前必须登录!