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

Raj*_*Vij 3 python django json httpresponse zipfile

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

我有一种情况,我正在遍历json列表,并希望以管理员视图的形式将所有这些返回为文件。

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
Run Code Online (Sandbox Code Playgroud)

现在,这只能让我返回/下载一个json文件,因为return会破坏循环。有没有更简单的方法将所有这些附加到单个响应对象中并返回该外部循环并以多个文件下载列表中的所有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
Run Code Online (Sandbox Code Playgroud)

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

小智 5

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

就像是:

    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'
Run Code Online (Sandbox Code Playgroud)