如何通知用户异步任务完成?

时间:2019-05-27 02:44:29

标签: ajax django multithreading

我正在使用线程库在Django中长时间运行。该过程完成后,我想在前端保持更新进度状态。我无法从线程函数将任何内容发布到ajax.get()。

View.py

def upload_handler(request, file_loc, filename):
    // do something with uploaded
    // I want to notify user that this process is complete via a post
class Uploader(View):
    def get(self, request):
        file=UploadForm()
        return render(request,'template.html',{'form':file}) #,'files':files})
    def post(self, request):
        file = UploadForm(data=request.POST, files=request.FILES)
        if file.is_valid():
            x = request.FILES['file']
            file.save()
            filename = str(request.FILES['file'])
            file_loc = os.path.join(BASE_DIR, 'media', 'images', filename)
            upload_thread = Thread(target=upload_handler, args=(request, file_loc, filename))
            upload_thread.start()
            return HttpResponseRedirect(reverse('imageupload'))

urls.py

urlpatterns = [
    path('', Uploader.as_view(), name='imageupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

ajax调用脚本

{ 
    $.ajax({
      type:"get",
      url:"/uploader",
      datatype:"json",
      success:function(data)
      {
        console.log(data);
        alert("Your file is processed now!");
      }
    });
}, 1000);

假设文件上传页面将保持打开状态,直到完成漫长的过程。

1 个答案:

答案 0 :(得分:0)

AJAX选项数据类型为“ json”,但视图未返回“ json”。