【问题标题】:Bottle: execute a long running function asynchronously and send an early response to the client?Bottle:异步执行长时间运行的函数并向客户端发送早期响应?
【发布时间】:2014-09-13 19:40:31
【问题描述】:
我正在开发的 Bottle 应用(在 CherryPy 后面)收到来自 HTTP 客户端的资源请求,这会导致执行可能需要几个小时才能完成的任务。我想发送一个早期的 HTTP 响应(例如,202 Accepted)并继续处理任务。有没有办法在不使用 MQ 库和单独使用 Python/Bottle 的情况下实现这一目标?
例如:
from bottle import HTTPResponse
@route('/task')
def f():
longRunningTask() # <-- Anyway to make this asynchronous?
return bottle.HTTPResponse(status=202)
【问题讨论】:
标签:
python
rest
python-2.7
asynchronous
bottle
【解决方案1】:
我知道这个问题已经有好几年了,但我发现 @ahmed 的回答毫无帮助,令人难以置信,我想我至少可以分享一下我是如何在我的应用程序中解决这个问题的。
我所做的只是利用 Python 现有的线程库,如下所示:
from bottle import HTTPResponse
from threading import Thread
@route('/task')
def f():
task_thread = Thread(target=longRunningTask) # create a thread that will execute your longRunningTask() function
task_thread.setDaemon(True) # setDaemon to True so it terminates when the function returns
task_thread.start() # launch the thread
return bottle.HTTPResponse(status=202)
使用线程可以让您保持一致的响应时间,同时仍然具有相对复杂或耗时的功能。
我使用了 uWSGI,所以请确保在 uWSGI 应用程序配置中启用线程,如果你这样做的话。