【问题标题】:how to start threads and wait for them to finish without blocking a Django server?如何在不阻塞 Django 服务器的情况下启动线程并等待它们完成?
【发布时间】:2022-08-22 22:17:57
【问题描述】:

我对 Django 有疑问。我有一个执行繁重处理(数据帧操作)的函数。此任务在发送包含必要信息的表单以启动繁重的处理后执行。

我试图用 Threading 为这个函数创建一个线程。问题是该进程在后台发送良好,不会阻塞服务器,除非出现错误。我认为这个错误是正常的。有 dash 组件 (django-plotly-dash) 依赖于繁重处理的结果,并且由于这个繁重的处理是在后台发送的,所以 django 直接传递给没有要显示的信息的 dash 组件,因此返回错误。所以我使用 Threading.join() 来等待繁重的处理完成,但它使整个服务器瘫痪。如何避免阻塞服务器并允许用户在页面之间导航而不阻塞整个服务器,因为正在进行繁重的处理?

这是一个执行示例:

def read_csv(request):
    heavy_treatment(some_args) # <-- this block the server and return a dash componant
    return redirect(other_function_for_view) # <-- this loads the view containing the result of the heavy processing

然后我决定创建一个线程:

def read_csv(request):
    t = threading.Thread(target=heavy_treatment, args=(some_args), daemon=False)
    t.start() # <-- Task is sent to background
    return redirect(other_function_for_view) # <-- Error : No result to display for dash componants

Error : Layout must be a dash component or a function that returns a dash component.

<div class={% plotly_class name=\'test_stackoverflow\' %}>
           {%plotly_app  name=\"test_stackoverflow\" ratio=1 %}
</div>

一个解决方案是等到线程完成然后显示结果:

def read_csv(request):
    t = threading.Thread(target=heavy_treatment, args=(some_args), daemon=False)
    t.start() # <-- Task is sent to background
    t.join() # <-- wait for thread to finish <-- This block the server again
    return redirect(other_function_for_view) # <-- redirect to html page and load dash components

但是这样做会阻止服务器,从而阻止用户在页面之间浏览。

我想做的是在后台运行任务,等待它完成然后加载视图而不阻塞整个服务器。

我想说明芹菜不适合我的工作,谢谢你没有提出这个解决方案

    标签: python django django-views


    【解决方案1】:

    您可以尝试使用Django Asynchronous support。它还没有完成,但是一些解决方案已经稳定了,你现在或很快就会找到你的解决方案。

    【讨论】:

    • 你能举一个小例子来说明如何使用它吗?即使使用伪代码,它也会对我有很大帮助
    • @RidhaKchouk 抱歉,我还没有这样的经验。而且我不想在提供建议时猜测。不过,Django 开发人员正在努力包含异步功能。
    猜你喜欢
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 2021-04-30
    • 2021-01-23
    • 1970-01-01
    相关资源
    最近更新 更多