Django-Ajax HttpResponse延迟


                    

我有一个django视图函数,如果条件为true,则调用另一个函数,该函数作为一个单独的进程调用,该视图返回一个状态变量,该变量显示是否调用了该函数,状态返回给 分配给按钮的ajax单击事件。

问题在于,当执行“ do_work”函数时,直到“ do_work”终止,Ajax成功函数才会运行。</ p>

查看功能/ update / </ p>

 如果条件:
         p =进程(target = do_work,args(pack,))
         p.daemon =真
         p.start()
         成功=“真实”
其他:
         成功=“假”
打印成功
返回HttpResponse(成功)
</ code> </ pre>

Ajax调用</ p>

  $('button.update')。click(function(){
                 id = $(this).attr('id');
                 $ .post(“ / update /”,{
                 包:id,
                 },函数(结果){
                     警报(结果);
                     });
                 返回false;
                 });
</ code> </ pre>

在两种情况下都立即执行“打印成功”,但是直到功能do_woks终止之前,警报不会弹出</ p>
     </ div>

展开原文

原文

I have a django view function that calls another function if a condition is true, the function is called as a separate process, the view returns a status variable which shows if the function was called or not, the status is returned to a ajax click event assigned to a button.
The problem is that when the function 'do_work' is executed ajax success function isn't run until 'do_work' terminates.

view function /update/

if condition:
        p = Process(target=do_work, args(pack,))
        p.daemon = True
        p.start()
        success = "True"
else:
        success = "False"
print success
return HttpResponse(success)

Ajax call

 $('button.update').click(function() {
                id = $(this).attr('id');
                $.post("/update/", {
                pack : id,
                }, function(result){
                    alert(result);
                    });
                return false;
                });

the 'print success' gets executed right away in both cases, but the alert wont pop up until the function do_woks terminates

1个回答


尽管您在返回HttpResponse(成功)</ code>之前看到了打印的消息,但是return语句本身无法异步完成响应。</ p>

大概在该函数返回之后,您的Web服务器仍在等待其他事情发生(例如,所有子进程终止),然后再完成响应。</ p>

对于Django中的异步任务,我强烈建议 Celery 。</ p>
     </ div>

展开原文

原文

Although you see the printed message before you return HttpResponse(success), that return statement in itself can't asynchronously finish the response.

Presumably after that function returns, your web server is still waiting for something else to happen (such as for all child processes to terminate) before it finishes the response.

For asynchronous tasks in Django I highly recommend Celery.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐