python - 如何在 HttpResponse Django 中返回多个文件

标签 python json django httpresponse zip

我一直在为这个问题绞尽脑汁。在 Django 中有没有一种方法可以从单个 HttpResponse 提供多个文件?

我有一个场景,我正在遍历一个 json 列表,并希望将所有这些作为文件从我的管理 View 中返回。

class CompanyAdmin(admin.ModelAdmin):
    form = CompanyAdminForm
    actions = ['export_company_setup']

    def export_company_setup(self, request, queryset):
        update_count = 0
        error_count = 0
        company_json_list = []
        response_file_list = []
        for pb in queryset.all():
            try:
                # get_company_json_data takes id and returns json for the company.
                company_json_list.append(get_company_json_data(pb.pk))
                update_count += 1
            except:
                error_count += 1

        # TODO: Get multiple json files from here.
        for company in company_json_list:
            response = HttpResponse(json.dumps(company), content_type="application/json")
            response['Content-Disposition'] = 'attachment; filename=%s.json' % company['name']
            return response
        #self.message_user(request,("%s company setup extracted and %s company setup extraction failed" % (update_count, error_count)))
        #return response

现在这只会让我返回/下载一个 json 文件,因为返回会打破循环。有没有更简单的方法将所有这些附加到单个响应对象中并返回该外部循环并将列表中的所有 json 下载到多个文件中?

我研究了一种将所有这些文件打包到一个 zip 文件中的方法,但我没有这样做,因为我能找到的所有示例都有带有路径和名称的文件,而在这种情况下我实际上没有。

更新:

我尝试集成 zartch 的解决方案以使用以下方法获取 zip 文件:

    import StringIO, zipfile
    outfile = StringIO.StringIO()
    with zipfile.ZipFile(outfile, 'w') as zf:
        for company in company_json_list:
            zf.writestr("{}.json".format(company['name']), json.dumps(company))
        response = HttpResponse(outfile.getvalue(), content_type="application/octet-stream")
        response['Content-Disposition'] = 'attachment; filename=%s.zip' % 'company_list'
        return response

因为我从来没有开始的文件,所以我考虑只使用我拥有的 json 转储并添加单独的文件名。这只会创建一个空的 zip 文件。我认为这是预期的,因为我确定 zf.writestr("{}.json".format(company['name']), json.dumps(company)) 不是这样做的方法它。如果有人可以帮助我,我将不胜感激。

最佳答案

也许如果您尝试将所有文​​件打包到一个 zip 中,您可以在管理中将其存档

类似于:

    def zipFiles(files):
        outfile = StringIO()  # io.BytesIO() for python 3
        with zipfile.ZipFile(outfile, 'w') as zf:
            for n, f in enumerate(files):
                zf.writestr("{}.csv".format(n), f.getvalue())
        return outfile.getvalue()

    zipped_file = zip_files(myfiles)
    response = HttpResponse(zipped_file, content_type='application/octet-stream')
    response['Content-Disposition'] = 'attachment; filename=my_file.zip'

关于python - 如何在 HttpResponse Django 中返回多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42814732/

相关文章:

python - 使用 Django 模型的 post_save 进行手动缓存失效 : do foreign keys trigger save()?

python - 提交后django清除表单字段

Python错误u'标签[-1]不在[索引]中'

php - 使用 JSON 更新查询失败

json - 用结构解码未命名的JSON数组swift 4

Django clean 方法在 POST 上抛出 KeyError

python - 父进程在python中终止时如何避免进程终止

python - 从 Python 启动另一个程序>单独<

python - 如何在分组数据框上使用 fillna?

java - 在java中更快地解析json