栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在更新时显示从Flask视图流式传输的数据

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在更新时显示从Flask视图流式传输的数据

您可以流式传输响应中的数据,但是不能按照描述的方式动态更新模板。模板在服务器端只渲染一次,然后发送到客户端。您需要使用Javascript读取流式响应并在客户端输出数据。

用于

XMLHttpRequest
向要发送数据的端点发出请求。然后定期从流中读取直到完成。

此示例假定一种非常简单的消息格式:一行数据,然后是换行符。当然,只要有一种识别每条消息的方法,解析就可能变得很复杂。例如,您可以返回一个JSON对象并在客户端上对其进行解码。

from time import sleepfrom flask import Flask, render_templatefrom math import sqrtapp = Flask(__name__)@app.route('/')def index():    # render the template (below) that will use Javascript to read the stream    return render_template('index.html')@app.route('/stream_sqrt')def stream():    def generate():        for i in range(500): yield '{}n'.format(sqrt(i)) sleep(1)    return app.response_class(generate(), mimetype='text/plain')app.run()<p>This is the latest output: <span id="latest"></span></p><p>This is all the output:</p><ul id="output"></ul><script>    var latest = document.getElementById('latest');    var output = document.getElementById('output');    var xhr = new XMLHttpRequest();    xhr.open('GET', '{{ url_for('stream') }}');    xhr.send();    var position = 0;    function handleNewData() {        // the response text include 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) { latest.textContent = value;  // update the latest value in place // build and append a new item to a list to log all output var item = document.createElement('li'); item.textContent = value; output.appendChild(item);        });        position = messages.length - 1;    }    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);</script>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/635068.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号