我正在尝试使用 Flask 应用程序生成大型 PDF。pdf 生成涉及生成十个长 pdf,然后将它们合并在一起。该应用程序使用带有以下标志的 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运行这段代码时,我没有得到定期更新。工作人员一直运行直到 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 的工人阶级中有一些东西可以用来确保正确处理流程?