代码之家  ›  专栏  ›  技术社区  ›  Vaibhav Vishal

已从视图向客户端发送有关长时间运行的任务进度的更新

  •  0
  • Vaibhav Vishal  · 技术社区  · 6 年前

    Found 100 rows of data
    Interesting 1/100.
    Interesting 2/100.
    ...
    Interesting 100/100.
    Done.
    

    import pandas as pd
    
    def myView(self, request):
        """Handle POST requests, save all data provided in excel file."""
        excel_file = request.FILES.get('excel_one')
        excel_df = pd.read_excel(excel_file)
        data_format = ['Option_1', 'Option_2', 'Option_3', 'Option_4',]
        try:
            formatted_df = excel_df[data_format]
        except KeyError as error:
            return JsonResponse({'success': False, 'message': str(error), })
        # forloop to create model objects
        for i, v in formatted_df.iterrows():
            # do a lot of data validating and stuff first
            MyModels.objects.create(arguments)
            print(f'Created object {i+1}/{len(formatted_df)}!'  # Want to to be sent to html page in real time
        return JsonResponse({'success': True, })
    

    我提出了如下ajax请求:

    $.ajax({  // variables url, data, etc. contain the expected stuff
        async: false,
        url: url,
        method: "POST",
        data: data,
        success: function(d){
            if(data.success){
                console.log(d);
             }
             else{
                 $('.log').append('<p><b>Error:</b> '+ d.message +'</p>')
             }
         },
         cache: false,
         contentType: false,
         processData: false
    });
    

    2 回复  |  直到 6 年前
        1
  •  2
  •   Bruno A. ruddra    6 年前

    • 快速而肮脏的方法:让JS轮询另一个API视图来检查状态
    • 你听说过吗 StreamingHttpResponse ? 我从来没用过,但也许值得一试。你可以看到一个例子 here
        2
  •  1
  •   Thomas John    6 年前

    Celery 对这里很有帮助。

    • 只需为我们耗时的任务编写一个函数,将其设置为芹菜任务
    • 立即返回进程id或文件作为第一个API的响应
    • 使用此id在ur ajax的第二个API上进行轮询,获得此API上的预期结果