gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:47 26 4
gpt4 key购买 nike

我一直在为这个问题绞尽脑汁。在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com