搜索
首页后端开发Python教程如何显示从 Flask 视图流式传输的实时数据?

How to Display Real-time Data Streamed from a Flask View?

实时显示从 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中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?May 03, 2025 am 12:11 AM

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

说明如何将内存分配给Python中的列表与数组。说明如何将内存分配给Python中的列表与数组。May 03, 2025 am 12:10 AM

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

您如何在Python数组中指定元素的数据类型?您如何在Python数组中指定元素的数据类型?May 03, 2025 am 12:06 AM

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

什么是Numpy,为什么对于Python中的数值计算很重要?什么是Numpy,为什么对于Python中的数值计算很重要?May 03, 2025 am 12:03 AM

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

讨论'连续内存分配”的概念及其对数组的重要性。讨论'连续内存分配”的概念及其对数组的重要性。May 03, 2025 am 12:01 AM

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

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

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

在Numpy阵列上可以执行哪些常见操作?在Numpy阵列上可以执行哪些常见操作?May 02, 2025 am 12:09 AM

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

Python的数据分析中如何使用阵列?Python的数据分析中如何使用阵列?May 02, 2025 am 12:09 AM

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

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

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

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

螳螂BT

螳螂BT

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

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

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