实时显示从 Flask 视图流式传输的数据
简介
处理实时数据时,通常希望在数据可用时显示数据。对于 Flask,这可能具有挑战性,因为模板仅在服务器端渲染一次。本文探讨了如何克服此限制,允许在更大的模板页面中动态显示流数据。
利用 JavaScript 和 XMLHttpRequest
最通用的方法包括使用 JavaScript 和 XMLHttpRequest 定期从流式端点检索数据。然后可以将接收到的数据动态添加到页面中。这可以完全控制输出及其呈现。
# Stream endpoint that generates sqrt(i) and yields it as a string @app.route("/stream") def stream(): def generate(): for i in range(500): yield f"{math.sqrt(i)}\n" time.sleep(1) return app.response_class(generate(), mimetype="text/plain")
<!-- Utilize JavaScript to handle streaming data updates --> <script> // Retrieve latest and historical values from streamed endpoint xhr.open("GET", "{{ url_for('stream') }}"); xhr.send(); var latest = document.getElementById("latest"); var output = document.getElementById("output"); var position = 0; function handleNewData() { // Split response, retrieve new messages, and track position var messages = xhr.responseText.split("\n"); messages.slice(position, -1).forEach(function (value) { latest.textContent = value; // Update latest value var item = document.createElement("li"); item.textContent = value; output.appendChild(item); }); position = messages.length - 1; } // Periodically check for new data and stop when stream ends var timer; timer = setInterval(function () { handleNewData(); if (xhr.readyState == XMLHttpRequest.DONE) { clearInterval(timer); latest.textContent = "Done"; } }, 1000); </script>
使用 Iframe** 方法
或者, iframe 可以显示流式 HTML 输出。虽然最初更容易实现,但它带来了一些缺点,例如增加资源使用和有限的样式选项。尽管如此,它对于某些场景还是很有用的。
# Stream endpoint that generates html output @app.route("/stream") def stream(): @stream_with_context def generate(): yield render_template_string('<link rel="stylesheet" href="%7B%7B%20url_for(" static filename="stream.css">') for i in range(500): yield render_template_string("<p>{{ i }}: {{ s }}</p>\n", i=i, s=math.sqrt(i)) sleep(1) return app.response_class(generate())
<!-- Using an iframe for displaying streamed HTML --> <p>This is all the output:</p> <iframe src="%7B%7B%20url_for(" stream></iframe>
结论
无论是使用 JavaScript 还是 iframe,Flask 都允许集成实时数据流入模板化网页。这些技术可以动态显示不断变化的数据,提供更具吸引力的实时用户体验。
以上是如何显示从 Flask 视图流式传输的实时数据?的详细内容。更多信息请关注PHP中文网其他相关文章!

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

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

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

Atom编辑器mac版下载
最流行的的开源编辑器

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

SublimeText3 Linux新版
SublimeText3 Linux最新版

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