Bottle: 如何异步执行长时间运行的函数并提前响应客户端?
我正在开发一个使用CherryPy的Bottle应用,这个应用会接收来自HTTP客户端的请求,这个请求会触发一个可能需要几个小时才能完成的任务。我想在任务还没完成的时候就提前发送一个HTTP响应,比如说202 Accepted
,然后继续处理这个任务。有没有办法在不使用消息队列库的情况下,仅用Python和Bottle来实现这个功能呢?
比如:
from bottle import HTTPResponse
@route('/task')
def f():
longRunningTask() # <-- Anyway to make this asynchronous?
return bottle.HTTPResponse(status=202)
1 个回答
4
我知道这个问题已经好几年了,但我觉得@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应用配置中启用线程功能。