抱歉,评论区放不下。每个请求最终都必须得到响应(或失败/超时)。如果您真的不需要向客户端返回任何数据,只需发送一个带有状态码的空响应即可。如果请求的处理需要时间,它应该异步运行,这就是 celery 的用武之地。因此,请求处理程序的阻塞实现:
def request_processor_long_running_blocking_func(request_data):
# process request data, which takes a lot of time
# result is probably written into db
pass
def request_handler_func(request):
request_processor_long_running_blocking_func(request.data)
return HttpResponse(status=200)
如果我理解正确,这是您试图通过request_processor_long_running_blocking_func
异步运行来避免的,因此request_handler_func
不会阻塞。这可以像这样用芹菜解决:
from celery.task import task
@task
def request_processor_long_running_blocking_func(request_data):
# the task decorator wraps your blocking function, with celery's Task class
# which has a delay method available for you to call, which will run your function
# asynchronously on one of your celery background worker processes
pass
def request_handler_func(request):
request_processor_long_running_blocking_func.delay(request.data)
# calling the function with delay won't block, it returns immediately
# and your response is sent back instantly
return HttpResponse(status=200)
还有一件事,用ajax发送这些任务请求,这样你的web界面就不会被重新加载或任何东西,所以用户可以在发送请求后继续使用你的应用程序