在更新时显示从烧瓶视图流的数据
我有一种生成数据并实时流式传输的视图。我不知道如何将这些数据发送到可以在HTML模板中使用的变量。我当前的解决方案只是在到达时将数据输出到空白页面,但我想将其包括在更大的页面中,并使用格式化。在将数据流传输到页面时,如何更新,格式化和显示数据?
import flask
import time, math
app = flask.Flask(__name__)
@app.route('/')
def index():
def inner():
# simulate a long process to watch
for i in range(500):
j = math.sqrt(i)
time.sleep(1)
# this value should be inserted into an HTML template
yield str(i) + '<br/>\n'
return flask.Response(inner(), mimetype='text/html')
app.run(debug=True)
I have a view that generates data and streams it in real time. I can't figure out how to send this data to a variable that I can use in my HTML template. My current solution just outputs the data to a blank page as it arrives, which works, but I want to include it in a larger page with formatting. How do I update, format, and display the data as it is streamed to the page?
import flask
import time, math
app = flask.Flask(__name__)
@app.route('/')
def index():
def inner():
# simulate a long process to watch
for i in range(500):
j = math.sqrt(i)
time.sleep(1)
# this value should be inserted into an HTML template
yield str(i) + '<br/>\n'
return flask.Response(inner(), mimetype='text/html')
app.run(debug=True)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在响应中流式传输数据,但是您不能以描述方式动态更新模板。该模板在服务器端渲染一次,然后发送到客户端。
一种解决方案是使用JavaScript读取流响应并在客户端输出数据。使用
XMLHTTPREQUEST
向将流传输数据的端点提出请求。然后定期从流读取直到完成。这引入了复杂性,但允许直接更新页面,并对输出的外观完全控制。下面的示例表明,通过显示所有值的当前值和日志。
此示例假设一个非常简单的消息格式:单个数据行,然后是新线。只要有一种方法可以识别每个消息,这可能会尽可能复杂。例如,每个循环都可以返回客户端解码的JSON对象。
一个
&lt; iframe&gt;
可用于显示流的HTML输出,但它具有一些缺点。框架是一个单独的文档,可增加资源使用情况。由于它仅显示流数据,因此可以像页面的其余部分那样对其进行样式。它只能附加数据,因此长量输出将在可见的滚动区域以下呈现。它无法根据每个事件修改页面的其他部分。index.html
用指向stream
endpoint的帧呈现页面。该框架具有相当小的默认尺寸,因此您可能需要进一步设置它。使用Render_template_string
知道要逃脱变量,以渲染每个项目的HTML(或使用更复杂的模板文件使用render_template
)。可以首先产生一条初始线以将CSS加载到框架中。You can stream data in a response, but you can't dynamically update a template the way you describe. The template is rendered once on the server side, then sent to the client.
One solution is to use JavaScript to read the streamed response and output the data on the client side. Use
XMLHttpRequest
to make a request to the endpoint that will stream the data. Then periodically read from the stream until it's done.This introduces complexity, but allows updating the page directly and gives complete control over what the output looks like. The following example demonstrates that by displaying both the current value and the log of all values.
This example assumes a very simple message format: a single line of data, followed by a newline. This can be as complex as needed, as long as there's a way to identify each message. For example, each loop could return a JSON object which the client decodes.
An
<iframe>
can be used to display streamed HTML output, but it has some downsides. The frame is a separate document, which increases resource usage. Since it's only displaying the streamed data, it might not be easy to style it like the rest of the page. It can only append data, so long output will render below the visible scroll area. It can't modify other parts of the page in response to each event.index.html
renders the page with a frame pointed at thestream
endpoint. The frame has fairly small default dimensions, so you may want to to style it further. Userender_template_string
, which knows to escape variables, to render the HTML for each item (or userender_template
with a more complex template file). An initial line can be yielded to load CSS in the frame first.迟到了5年,但实际上可以按照您最初尝试这样做的方式进行,JavaScript完全不必要(编辑:被接受答案的作者在我写这本书后添加了iframe部分。您只需要将输出作为
&lt; iframe&gt;
:然后,'index.html.jinja'文件将包含
&lt; iframe&gt;
和内容url作为SRC,它类似:当渲染用户提供的数据
render_template_string()
时,应用于渲染内容以避免注入攻击。但是,我从示例中排除了这一点,因为它增加了额外的复杂性,不在问题的范围之内,与OP无关,因为他没有流式传输用户提供的数据,并且与广泛的数据无关大多数人看到这篇文章,因为流媒体提供用户提供的数据是一个遥远的情况,如果有任何人必须这样做的话,很少有人。5 years late, but this actually can be done the way you were initially trying to do it, javascript is totally unnecessary (Edit: the author of the accepted answer added the iframe section after I wrote this). You just have to include embed the output as an
<iframe>
:Then the 'index.html.jinja' file will include an
<iframe>
with the content url as the src, which would something like:When rendering user-provided data
render_template_string()
should be used to render the content to avoid injection attacks. However, I left this out of the example because it adds additional complexity, is outside the scope of the question, isn't relevant to the OP since he isn't streaming user-provided data, and won't be relevant for the vast majority of people seeing this post since streaming user-provided data is a far edge case that few if any people will ever have to do.最初,我有一个类似的问题,与发布的问题相似,在这里正在训练模型并在HTML中进行固定并格式化。以下答案是用于将来的参考或试图解决相同问题并需要灵感的人。
一个很好的解决方案是在JavaScript中使用EventSource,如所述在这里。可以使用上下文变量启动此侦听器,例如从表单或其他来源。通过发送停止命令来停止听众。在此示例中,使用睡眠命令可进行可视化。最后,可以使用JavaScript Dom-manipulation实现HTML格式。
烧瓶应用程序
HTML模板
Originally I had a similar problem to the one posted here where a model is being trained and the update should be stationary and formatted in Html. The following answer is for future reference or people trying to solve the same problem and need inspiration.
A good solution to achieve this is to use an EventSource in Javascript, as described here. This listener can be started using a context variable, such as from a form or other source. The listener is stopped by sending a stop command. A sleep command is used for visualization without doing any real work in this example. Lastly, Html formatting can be achieved using Javascript DOM-Manipulation.
Flask Application
HTML Template