Python 如何在不重新加载 Flask 页面的情况下显示闪烁的消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40949746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display flashing message without reloading the page in Flask?
提问by trm0808
I'm working on a web application using Flask in Python.
我正在使用 Python 中的 Flask 开发一个 Web 应用程序。
I have small function in my application that calculates some values in the background and displays the result on the web page via a flashing message.
我的应用程序中有一个小函数,可以在后台计算一些值并通过闪烁的消息在网页上显示结果。
Everything is displaying and working fine but it requires page reloading to get the flashing message.
一切都显示和工作正常,但需要重新加载页面才能获得闪烁的消息。
I want to display messages without reloading page.
我想在不重新加载页面的情况下显示消息。
I heard that I can do that with js, but I'm not familiar with js.
我听说我可以用 js 做到这一点,但我对 js 不熟悉。
If you have any ideas or suggestion I would appreciate.
如果您有任何想法或建议,我将不胜感激。
There is my code that could build a better picture of what I'm doing.
我的代码可以更好地了解我正在做的事情。
This is the renderer between my app and the main html file
这是我的应用程序和主 html 文件之间的渲染器
{% macro render_field(field) %}
<dt> {{ field.label }}
<dd> {{ field(**kwargs)|safe }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</dd>
{% endmacro %}
This is the html file were I want to display flashing messages:
这是我想显示闪烁消息的 html 文件:
<div class="container-fluid" style="min-height:100%">
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{message}}
</div>
{% endfor %}
{% endif %}
{% endwith %}
</div>
回答by boardrider
Here's what Flask Web Development: Developing Web Applications with Python (pp. 46-48)has to say of Message Flashing:
以下是Flask Web 开发:使用 Python 开发 Web 应用程序(第 46-48 页)对消息闪烁的评论:
Sometimes it is useful to give the user a status update after a request is completed. This
could be a confirmation message, a warning, or an error. A typical example is when you
submit a login form to a website with a mistake and the server responds by rendering
the login form again with a message above it that informs you that your username or
password is invalid.
Flask includes this functionality as a core feature. Example 4-6 shows how the flash()
function can be used for this purpose.
有时在请求完成后向用户提供状态更新很有用。这可能是确认消息、警告或错误。一个典型的例子是,当您向网站提交登录表单时出错,服务器通过再次呈现登录表单并在其上方显示一条消息作为响应,通知您您的用户名或密码无效。Flask 将此功能作为核心功能包含在内。示例 4-6 显示了如何将flash()
函数用于此目的。
Example 4-6. hello.py: Flashed messages
例 4-6。hello.py:闪现的消息
@app.route('/', methods=['GET', 'POST'])
def index():
form = Nameform()
if form.validate_on_submit():
old_name = session.get('name')
if old_name is not None and old_name != form.name.data:
flash('Looks like you have changed your name!')
session['name'] = form.name.data
form.name.data = ''
return redirect(url_for('index'))
return render_template('index.html', form=form, name=session.get('name'))
form = form, name = session.get('name'))
In this example, each time a name is submitted it is compared against the name stored
in the user session, which would have been put there during a previous submission of
the same form. If the two names are different, the flash()
function is invoked with a
message to be displayed on the next response sent back to the client.
在此示例中,每次提交名称时,都会将其与存储在用户会话中的名称进行比较,该名称会在之前提交相同表单时放在那里。如果这两个名称不同,flash()
则调用该函数并在下一个发送回客户端的响应中显示一条消息。
Calling flash()
is not enough to get messages displayed; the templates used by the
application need to render these messages. The best place to render flashed messages is
the base template, because that will enable these messages in all pages. Flask makes a
get_flashed_messages()
function available to templates to retrieve the messages and
render them, as shown in Example 4-7.
呼叫flash()
不足以显示消息;应用程序使用的模板需要呈现这些消息。呈现闪现消息的最佳位置是基本模板,因为这将在所有页面中启用这些消息。Flaskget_flashed_messages()
为模板提供了一个
函数来检索消息并渲染它们,如例 4-7 所示。
Example 4-7. templates/base.html: Flash message rendering
例 4-7。模板/base.html:Flash 消息呈现
{% block content %}
<div class="container">
{% for message in get_flashed_messages() %}
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ message }}
</div>
{% endfor %}
{% block page_content %}{% endblock %}
</div>
{% endblock %}
In this example, messages are rendered using Bootstrap's alert CSS styles for warning messages (one is shown in Figure 4-4).
在此示例中,消息使用 Bootstrap 的警报 CSS 样式来呈现警告消息(如图 4-4 所示)。
Figure 4-4. Flashed message
图 4-4。闪现的消息
A loop is used because there could be multiple messages queued for display, one for
each time flash()
was called in the previous request cycle. Messages that are retrieved from get_flashed_messages()
will not be returned the next time this function is called,
so flashed messages appear only once and are then discarded.
使用循环是因为可能有多个消息排队等待显示,flash()
在前一个请求周期中每次调用一个。get_flashed_messages()
下一次调用此函数时不会返回从中检索到的消息,因此闪现的消息仅出现一次,然后被丢弃。
回答by Preston Hager
This is not possible via Python without reloading the page. You must do this in javascript. I suggest CSS styling with display: none
and display: block
. Here is an example.
在不重新加载页面的情况下,这是不可能通过 Python 实现的。您必须在 javascript 中执行此操作。我建议使用display: none
和 进行CSS 样式设置display: block
。这是一个例子。
1) Python Code, this should go in your app.py
or flask.py
file.
1) Python 代码,这应该在您的app.py
或flask.py
文件中。
app.route('/flash/<message>')
def flash(message):
return render_template('flash.html', msg=message)
This will render the HTML page named flash.html
. The URL passed in will also have another argument, <message>
this is the message that will flash. A URL like this, localhost:80/flash/Hello%20World!
will flash the message "Hello World!" on your screen.
这将呈现名为 的 HTML 页面flash.html
。传入的 URL 也会有另一个参数,<message>
这是会闪烁的消息。像这样的 URLlocalhost:80/flash/Hello%20World!
会闪烁消息“Hello World!” 在你的屏幕上。
There is also another way to pass a message in, this is will arguments. The code for that is like so.
还有另一种传递消息的方法,这是将参数。代码是这样的。
app.route('/flash')
def flash():
message = request.args.get("msg")
return render_template("flash.html", ,msg=message)
This uses the flask's request arguments. So a URL like this, localhost:80/flash?msg=Hello%20World!
will give a flashing message saying "Hello World!". If you want to use this method be sure to have the import statement, from flask import request
in your import statements.
这使用烧瓶的请求参数。所以像这样的 URLlocalhost:80/flash?msg=Hello%20World!
会给出一条闪烁的消息,说“Hello World!”。如果要使用此方法,请确保from flask import request
在您的导入语句中具有导入语句。
2) Html Code, this is a separate file named, flash.html
in your templates folder.
2) Html 代码,这是一个名为的单独文件,flash.html
位于您的模板文件夹中。
<body>
<h1 id="header">{{ message }}</h1>
<script>
var heading = $("#header");
setInterval(function() {
if (heading.style.display == "block") { heading.style.display = "none"; }
else if (heading.style.display == "none") { heading.style.display = "block"; }
}, 1000);
</script>
</body>
The 1000
in the setInterval is milliseconds. So the heading will blinkevery 2 seconds.
该1000
在的setInterval是毫秒。所以标题会每 2 秒闪烁一次。
回答by hamx0r
You may want to consider using Toastrinstead. I ran into the same roadblock with Flask's Flash feature, and Toastr is pure JS. You can use it just like a console log line in your code
您可能需要考虑改用Toastr。我遇到了与 Flask 的 Flash 功能相同的障碍,而 Toastr 是纯 JS。您可以像代码中的控制台日志行一样使用它
toastr.info("Here's a message to briefly show to your user");
toastr.info("Here's a message to briefly show to your user");