Flask:处理输入时,服务器发送事件(SSE)流功能停止 [英] Flask: Server-sent event (SSE) stream function is halted when processing input

查看:117
本文介绍了Flask:处理输入时,服务器发送事件(SSE)流功能停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理与

I'm working on a problem very similar to this one (lots of code copied from there): Displaying a progress bar for processing an input uploaded via a html form.

HTML:

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

      // Event source closed after hitting 100%
      if(event.data == 100){
        source.close()
      }
    }
  }
  </script>

  <body>
    <div class="container">
      ...
      <form method="POST" action="/process" enctype="multipart/form-data">
        <div class="form-group">
        ...
          <input type="file" name="file">
          <input type="submit" name="upload" onclick="getProgress()" />
        </div>
      </form>

      <div class="progress" style="width: 80%; margin: 50px;">
        <div class="progress-bar progress-bar-striped active"
          role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
          <span class="progress-bar-label">0%</span>
        </div>
      </div>
    </div>
  </body>

app.py:


@app.route('process')
def process_inputs():
    ...
    r.set("progress", progress)
    ...


@app.route('/progress')
def progress():

  def progress_stream():
    progress = r.get("progress")
    while progress < 100:
      yield "data:" + str(progress) + "\n\n"

      time.sleep(1)

  return Response(progress_stream(), mimetype='text/event-stream')

据我了解,progressprocess_input函数应同时运行,因此progress可以在处理进行时更新进度条.但是,由于progress被暂停直到``process_input`完成为止,这是行不通的.

From my understanding, the progress and process_input functions should run simultaneously, so progress can get update the progress bar while the processing takes place. However, this doesn't work since progress is halted until ``process_input` is finished.

如何使这两个功能同时运行?我认为这将由Flask的threaded功能自动处理.

How can I get these two function to run simultaneously? I thought this would automatically be handled by Flask's threaded functionality.

推荐答案

显然是浏览器问题:使用Chrome可以按预期运行,但不能使用Firefox.看起来Firefox在等待POST请求(?)时不处理传入的SSE

Apparently it's a browser issue: with Chrome it works as intended, but not with Firefox. Looks like Firefox doesn't process incoming SSEs while waiting on the POST-request (?)

这篇关于Flask:处理输入时,服务器发送事件(SSE)流功能停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆