我正在使用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 %}Run Code Online (Sandbox Code Playgroud)
这是我希望显示闪烁消息的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>Run Code Online (Sandbox Code Playgroud)
boa*_*der 11
以下是Flask Web开发:使用Python开发Web应用程序(第46-48页)对Message Flashing的说法:
有时,在请求完成后为用户提供状态更新很有用.这可能是确认消息,警告或错误.一个典型的例子是,当您向网站提交登录表单时出现错误,服务器通过再次使用上面的消息呈现登录表单来响应,通知您用户名或密码无效.Flask将此功能作为核心功能.例4-6显示了该flash()
功能如何用于此目的.
例4-6.hello.py:闪烁的消息
在此示例中,每次提交名称时,都会将其与存储在用户会话中的名称进行比较,该名称将在之前提交的同一表单中放置.如果两个名称不同,flash()则调用该函数,并在下一个发送回客户端的响应中显示一条消息.
调用flash()不足以显示消息; 应用程序使用的模板需要呈现这些消息.呈现闪烁消息的最佳位置是基本模板,因为这将在所有页面中启用这些消息.Flask get_flashed_messages()为模板提供了一个
函数来检索消息并呈现它们,如例4-7所示.
例4-7.templates/base.html:Flash消息呈现
在此示例中,使用Bootstrap的警报CSS样式呈现消息以显示警告消息(如图4-4所示).
图4-4.闪烁的消息
使用循环是因为可能有多个消息排队等待显示,每次一个消息flash()在前一个请求循环中被调用.get_flashed_messages()下次调用此函数时,将不会返回从中检索的消息,因此闪烁的消息只出现一次,然后被丢弃.
在不重新加载页面的情况下,这是不可能通过 Python 实现的。您必须在 javascript 中执行此操作。我建议使用display: none和 进行CSS 样式设置display: block。这是一个例子。
1) Python 代码,这应该在您的app.py或flask.py文件中。
app.route('/flash/<message>')
def flash(message):
return render_template('flash.html', msg=message)
Run Code Online (Sandbox Code Playgroud)
这将呈现名为 的 HTML 页面flash.html。传入的 URL 也会有另一个参数,<message>这是会闪烁的消息。像这样的 URLlocalhost:80/flash/Hello%20World!将闪烁消息“Hello World!” 在你的屏幕上。
还有另一种传递消息的方法,这是将参数。代码是这样的。
app.route('/flash')
def flash():
message = request.args.get("msg")
return render_template("flash.html", ,msg=message)
Run Code Online (Sandbox Code Playgroud)
这使用烧瓶的请求参数。所以像这样的 URLlocalhost:80/flash?msg=Hello%20World!会给出一条闪烁的消息,说“Hello World!”。如果要使用此方法,请确保from flask import request在您的导入语句中具有导入语句。
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>
Run Code Online (Sandbox Code Playgroud)
该1000在的setInterval是毫秒。所以标题会每 2 秒闪烁一次。
| 归档时间: |
|
| 查看次数: |
24779 次 |
| 最近记录: |