显示更新时从 Flask 视图流式传输的数据
简介
在 Flask 应用程序中,通常需要显示实时生成或更新的数据。虽然 Flask 内置了对流响应的支持,但将此数据合并到 HTML 模板中可能具有挑战性。本文探讨了如何在数据流式传输到页面时动态更新、格式化和显示数据。
在 Flask 中流式传输数据
要在 Flask 中流式传输数据,您需要可以使用生成器作为对路线的响应。每次迭代响应时,生成器都会向客户端生成一块数据。例如:
@app.route('/') def index(): def inner(): for i in range(500): # simulate a long process to watch 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')
此代码模拟一个每秒生成值的长时间运行的进程。然后这些值以 HTML 片段的形式流式传输到响应。
在 JavaScript 中处理流式数据
虽然 Flask 支持流式响应,但 HTML 模板在服务器端渲染一次并且不能动态更新。要在浏览器中处理流数据,您可以使用 JavaScript 向端点发出请求,并在流数据到达时对其进行处理。
一种方法是使用 XMLHttpRequest (XHR) 对象创建一个请求流端点。然后,您可以从响应中读取数据,直至完成。下面是一个示例:
var xhr = new XMLHttpRequest(); xhr.open('GET', '{{ url_for('stream') }}'); xhr.send(); var position = 0; function handleNewData() { // the response text includes the entire response so far // split the messages, then take the messages that haven't been handled yet // position tracks how many messages have been handled // messages end with a newline, so split will always show one extra empty message at the end var messages = xhr.responseText.split('\n'); messages.slice(position, -1).forEach(function(value) { // Update the displayed data using JavaScript latest.textContent = value; // update the latest value in place // Append the current value to a list to log all output var item = document.createElement('li'); item.textContent = value; output.appendChild(item); }); position = messages.length - 1; } // Check for new data periodically var timer; timer = setInterval(function() { // check the response for new data handleNewData(); // stop checking once the response has ended if (xhr.readyState == XMLHttpRequest.DONE) { clearInterval(timer); latest.textContent = 'Done'; } }, 1000);
此 JavaScript 代码使用 XMLHttpRequest 对象创建对流端点的请求。然后它会设置一个计时器来定期检查新数据并相应地更新页面。
使用 iframe 进行流式 HTML 输出
显示从流式传输的数据的另一种方法Flask视图就是使用iframe。 iframe 是一个单独的文档,可用于显示流式 HTML 输出。下面是一个示例:
@app.route('/stream') def stream(): @stream_with_context def generate(): # Serve initial CSS to style the iframe yield render_template_string('<link rel="stylesheet" href="%7B%7B%20url_for(" static filename="stream.css">') # Continuously stream HTML content within the iframe for i in range(500): yield render_template_string('<p>{{ i }}: {{ s }}</p>\n', i=i, s=sqrt(i)) sleep(1) return app.response_class(generate())
<p>This is all the output:</p> <iframe src="%7B%7B%20url_for('stream')%20%7D%7D"></iframe>
此代码使用stream_with_context 装饰器来增强生成器以支持其他功能。它提供初始 CSS 来设置 iframe 的样式,并在 iframe 中持续流式传输 HTML 内容。 iframe 中的 HTML 模板可以更复杂,并且可以根据需要包含不同的格式。
以上是如何动态更新和显示从 Flask 视图流式传输的数据?的详细内容。更多信息请关注PHP中文网其他相关文章!

Tomergelistsinpython,YouCanusethe操作员,estextMethod,ListComprehension,Oritertools

在Python3中,可以通过多种方法连接两个列表:1)使用 运算符,适用于小列表,但对大列表效率低;2)使用extend方法,适用于大列表,内存效率高,但会修改原列表;3)使用*运算符,适用于合并多个列表,不修改原列表;4)使用itertools.chain,适用于大数据集,内存效率高。

使用join()方法是Python中从列表连接字符串最有效的方法。1)使用join()方法高效且易读。2)循环使用 运算符对大列表效率低。3)列表推导式与join()结合适用于需要转换的场景。4)reduce()方法适用于其他类型归约,但对字符串连接效率低。完整句子结束。

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python的关键特性包括:1.语法简洁易懂,适合初学者;2.动态类型系统,提高开发速度;3.丰富的标准库,支持多种任务;4.强大的社区和生态系统,提供广泛支持;5.解释性,适合脚本和快速原型开发;6.多范式支持,适用于各种编程风格。

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

SublimeText3汉化版
中文版,非常好用