使用相同的视图来管理 ajax 和非 ajax 请求:如何运行一个函数来返回带有 zip 文件夹的 HttpResponse?

问题描述

我认为要么运行 celery 任务以生成 zip 文件仅当 zip 文件夹不存在时显示一条用户消息,其中包含一个允许用户下载 zip 文件夹的链接任务完成时(用户单击链接调用导出:下载视图)

但由于任务可能需要很长时间,我想限制每天运行一次此任务

如果 zip 文件夹已经存在(由用户内容和日期标识),我希望下载 zip floder,而不是运行任务

但我并没有这样做。

我尝试实现一个等效于下载视图但没有返回任何内容函数

我还考虑过使用使用 JQuery 调用下载视图的链接切换导出按钮(运行导出视图),但它非常复杂,正在寻找更简单的方法

'''
    Ajax query to export filtered data
'''
@login_required
def export(request):

    ...
    if zipexist:

        # -> HERE SHOULD call function to return ZIP folder already existing

        return JsonResponse ({"zip_exist": True},status = 200)
    else:
        if request.is_ajax() and request.method == "POST": 
            # asynchronous task using celery
            task = filtered_export.delay(user.id,study.id,database.id,selected_import,data,datadictionnary)

            return JsonResponse(
                {   
                    "zip_exist": False,'html': render_to_string(
                        'export/_message.html',{
                            'study':study,'database':database,'is_apiinfos': is_apiinfos,'selected_import': selected_import,'task': 'export','task_id': task.task_id
                        } # context
                    )
                },status=200
            )
    return JsonResponse ({"response": "error"},status = 400)

   
'''
    View that allowed user to download zip folder he has just produce by clicking export button (link to download available at end of task)
'''
@login_required
def download(request,study,database,date):
 
    ...

    # open the zip folder produce by user
    zipfile = open(path + username + '_' + ''.join(study.name.split()).lower() + '_' + ''.join(database.name.split()).lower() + '_' + selected_import + '.zip','rb')
    response = HttpResponse(zipfile)
    response['Content-Type'] = 'application/x-zip-compressed'
    response['Content-disposition'] = 'attachment; filename=' + ''.join(study.name.split()).lower() + '_' + ''.join(database.name.split()).lower() + '_' + selected_import + '.zip'
    
    return response

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)