+-
python-如何在HttpResponse Django中返回多个文件
我一直在为这个问题绞尽脑汁. 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

现在,这只会让我返回/下载一个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

由于我从没有开始的文件,所以我考虑只使用我拥有的json转储并添加单个文件名.这只会创建一个空的zipfile.我认为这是可以预期的,因为我确信zf.writestr(“ {}.json” .format(company [‘name’]),json.dumps(company))并非做到这一点.如果有人可以帮助我,我将不胜感激.

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

就像是:

def zipFiles(files):
    outfile = StringIO() # io.BytesIO() for python 3
    with zipfile.ZipFile(outfile, 'w') as zf:
        for n, f in enumarate(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中返回多个文件 - 乐贴网