python 具有长 运行 进程的 WSGI

python WSGI with long running process

我正在尝试编写一个简单的 WSGI 兼容应用程序来响应 HTTP POST,向服务器发送一些数据,关闭连接,然后 继续执行几秒。

这是一个较长的 运行ning,但不是很长的 运行ning 过程。我必须在 3 秒内响应并关闭连接 (Slack),但我的程序可能需要 5 秒左右才能真正 运行。我可以 运行 有足够的 WSGI 进程来处理负载,即使是 5 秒。

这是一个例子:

import time

def application(environ, start_response):
    start_response('200 OK', [('Content-type', 'text/plain')])
    yield "foo\n".encode()
    # we're done responding to the server, close the connection

    time.sleep(5)
    with open('/tmp/foo', 'w') as stream:
        stream.write('output stuff\n')

在这个例子中,yield 正确地刷新了东西,但我想继续执行。我可以做一个叉子,然后 return() 在父级中, 就像我希望这是一个 CGI 脚本一样,但我不高兴拥有所有 未关闭的 WSGI 状态。

我正在使用 Python 3.5 和 mod_wsgi 进行测试,但我希望它是 generic/compliant。

有没有想过线程池模型?您可以有一个生产者-消费者队列。只需 post 从 WSGI 应用程序进入队列并立即 return。这项工作将在不同的线程中完成。

最后,代码很琐碎,我会自己回答:

@app.route("/foo", methods=['POST'])
def slack_request():
    """Process a slash-command POST request from Slack"""
    query = QuerySlack(app.config, app.mdb, reporter)
    job = Thread(target=query, args=(response.form['query'],))
    job.start()
    try:
        return "processing {}...".format(' '.join(response.form['query']))
    except (ReportError, QueryError) as err:
        return str(err)