在Django视图中有效使用ThreadPoolExecutor

2024-04-18 17:53:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是使用ThreadPoolExecutor将一些长时间运行的任务卸载到异步线程。任务作为Django视图的一部分被触发,但是工作似乎并不是异步发生的(响应挂起大约10秒,即整个任务在返回之前完成)。我真的必须把ThreadPoolExecutor代码放到视图中吗?为什么?我不应该这样做吗(我目前的方法):

class SomeDjangoView(TemplateView):
    template_name = 'template_and_that.html'

    def get(self, request):
        clever_async_function()
        return render(request, self.template_name)

# Some other file
def clever_async_function():
    with ThreadPoolExecutor(max_workers=4) as executor:
        executor.map(long_running_task, iterable_models_or_similar)

我知道如果它真的很复杂,我应该设置一些类似芹菜的东西,但我正在努力保持轻量级目前。在


Tags: django代码nameself视图目标asyncrequest