Bottle:异步执行长时间运行的函数并向客户端发送早期响应?

问题描述 投票:1回答:1

我正在处理的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个回答
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应用程序配置中启用线程,如果这是你的方式。

© www.soinside.com 2019 - 2024. All rights reserved.