通过 Gunicorn + Flask 加载事件流

Loading an eventstream through Gunicorn + Flask

我正在尝试使用 Flask 应用程序生成大型 PDF。 pdf 生成涉及生成十个长 pdf,然后将它们合并在一起。应用程序 运行s 使用带有标志的 Gunicorn:--worker-class gevent --workers 2.

这是我的服务器端代码:

@app.route ('/pdf/create', methods=['POST', 'GET'])
def create_pdf():
    def generate():
        for section in pdfs:
            yield "data: Generating %s pdf\n\n" % section
            # Generate pdf with pisa (takes up to 2 minutes)

        yield "data:  Merging PDFs\n\n"
        # Merge pdfs (takes up to 2 minutes)
        yield "data: /user/pdf_filename.pdf\n\n"

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

客户端代码如下:

var source = new EventSource(create_pdf_url);
source.onopen = function (event) {
  console.log("Creating PDF")
}
source.onmessage = function (event) {
    console.log(event.data);
}
source.onerror = function (event) {
    console.log("ERROR");
}

当我 运行 没有 GUnicorn 时,我会从控制台日志中获得稳定、实时的更新。它们看起来像:

Creating PDF
Generating section one
Generating section two
Generating section three
...
Generating section ten
Merging PDFS
/user/pdf_filename.pdf

当我运行此代码 Gunicorn 时,我没有得到定期更新。工作人员 运行s 直到 Gunicorn 的超时终止它,然后我得到所有应该发生的消息的转储,然后是最终错误

Creating PDF
Generating section one
Generating section two
ERROR

Gunicorn 日志如下所示:

[2015-03-19 21:57:27 +0000] [3163] [CRITICAL] WORKER TIMEOUT (pid:3174)

如何防止 Gunicorn 终止进程?我不认为设置超长超时是个好主意。也许 gunicorn 的 worker classes 中有一些东西可以用来确保流程得到正确处理?

我最终使用 Celery 解决了这个问题。

我使用 this example 来指导我设置 Celery。

然后我使用 Grinberg's Celery tutorial 将实时更新流式传输到用户的浏览器。