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



我正在使用线程库在 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({
      type:"get",
      url:"/uploader",
      datatype:"json",
      success:function(data)
      {
        console.log(data);
        alert("Your file is processed now!");
      }
    });
}, 1000);

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

AJAX 选项数据类型为 "json",但视图不返回 "json"。

最新更新