我正在使用 Python 中的 Flask 开发 Web 应用程序。
我的应用程序中有一个小功能,可以在后台计算一些值并通过闪烁的消息在网页上显示结果。
一切都在显示并且工作正常,但需要重新加载页面才能获得闪烁的消息。
我想在不重新加载页面的情况下显示消息。
听说用js可以做到,但是我对js不熟悉。
如果您有任何想法或建议,我将不胜感激。
我的代码可以更好地描述我正在做的事情。
这是我的应用程序和主 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 %}
这是我要显示闪烁消息的 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>
最佳答案
这是Flask Web Development: Developing Web Applications with Python (pp. 46-48)不得不说消息闪烁:
有时在请求完成后向用户提供状态更新很有用。这个
可以是确认消息、警告或错误。一个典型的例子是当你
向网站提交登录表单错误,服务器通过渲染响应
登录表单再次出现,上面有一条消息,通知您您的用户名或
密码无效。
Flask 将此功能作为核心功能包括在内。例 4-6 展示了 flash()
函数可用于此目的。
示例 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'))
在此示例中,每次提交名称时,都会将其与存储的名称进行比较
在用户 session 中,在之前提交
相同的形式。如果两个名称不同,则调用 flash()
函数
在发送回客户端的下一个响应中显示的消息。
调用 flash()
不足以显示消息;使用的模板
应用程序需要呈现这些消息。呈现闪烁消息的最佳位置是
基本模板,因为这将在所有页面中启用这些消息。 Flask 使一个
get_flashed_messages()
函数可用于模板检索消息和
渲染它们,如示例 4-7 所示。
示例 4-7。 templates/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 %}
在本例中,消息是使用 Bootstrap 的 alert CSS 样式呈现的,用于警告 消息(一个如图4-4所示)。
图 4-4。闪烁的消息
使用循环是因为可能有多个消息排队等待显示,一个用于
每次在上一个请求周期中调用 flash()
。从 get_flashed_messages()
中检索到的消息将不会在下次调用此函数时返回,
所以闪烁的消息只出现一次然后被丢弃。
关于python - 如何在不重新加载 Flask 页面的情况下显示闪烁的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40949746/