【问题标题】:How to implement Server-Sent Events in Flask framework?如何在 Flask 框架中实现服务器发送事件?
【发布时间】:2020-08-06 12:42:08
【问题描述】:

我正在尝试让进度条在 Flask 中工作。我为此使用Server Sent Events。当我在本地开发服务器上运行它时,一切正常,我可以在浏览器中看到 /progress 窗口中实时添加的数字,并且进度条没有问题。

但是如果我在 Linux 服务器(Linode)中运行它,那么浏览器窗口会挂起 10 秒,然后进度条跳到 100。我是初学者,不明白为什么它在本地机器上工作,为什么在远程机器上不工作服务器。请有人解释。还有 - 这将是一个实用的解决方案。

Flask - app.py

@app.route('/progress')
def progress():
    def progress_func():
        x = 0
        while x < 100:
            time.sleep(1)
            x = x + 10
            yield 'data:' + str(x) + "\n\n"
    return Response(progress_func(), mimetype='text/event-stream')

js

var source = new EventSource("/progress");
source.onmessage = function(event) {
    $('.progress-bar').css('width', event.data+'%').attr('aria-valuenow', event.data);
    };

index.html

<div>
    <div class="progress" style="width: 100%; height: 6px;">
    <div class="progress-bar bg-success" role="progressbar" style="width: 6px" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>

【问题讨论】:

    标签: javascript python flask server


    【解决方案1】:

    根据我的经验,问题可能是由烧瓶和前端之间的反向代理引起的。

    如果您使用 nginx,则需要将 proxy_buffering 设置为 off 才能使用 SSE

    编辑:

    在查看http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering 时,我注意到您可以通过在烧瓶响应中将X-Accel-Buffering 标头设置为no 来获得相同的结果。此解决方案更好,因为它仅限于此特定响应。

    【讨论】:

      猜你喜欢
      • 2012-08-27
      • 2012-02-16
      • 1970-01-01
      • 2023-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多