如何在HttpResponse Django中返回多个文件 [英] How to return multiple files in HttpResponse Django
问题描述
我一直在为这个问题而绞尽脑汁. django中是否有一种方法可以从单个HttpResponse提供多个文件?
I have been wracking my brains in this problem. Is there a way in django to serve multiple files from a single HttpResponse?
我有一种情况,我正在遍历json列表,并希望以管理员视图的形式将所有这些返回为文件.
I have a scenario where i am looping through a list of json and want to return all those as file form my admin 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文件,因为return会中断循环.是否有一种更简单的方法将所有这些附加在单个响应对象中,然后返回该外部循环,并将列表中的所有json下载到多个文件中?
Now this will only let me return/download one json file as return would break the loop. Is there a simpler way to just append all this in a single response object and return that outside loop and download all json in the list in multiple files?
我研究了一种将所有这些文件包装成zip文件的方法,但是我没有这样做,因为我可以找到的所有示例都包含带有路径和名称的文件,而在这种情况下我并没有这些文件.
I looked through a way to wrap all these files into a zip file, but i failed to do so as all the examples that i could find had files with path and name which i don't really have in this case.
更新:
我尝试使用以下方法集成zartch的解决方案以获取zip文件:
I tried to integrate zartch's solution to get a zip file using following:
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))
不是做到这一点的方法.如果有人可以帮助我,我将不胜感激.
Since i never had the files to begin with, i thought about just using json dump that i had and adding individual filename. This just creates an empty zipfile. Which i think is expected as i am sure zf.writestr("{}.json".format(company['name']), json.dumps(company))
is not the way to do it. I would appreciate if anyone can help me with this.
推荐答案
也许,如果您尝试将所有文件打包在一个zip中,则可以在Admin中存档
Maybe if you try to pack all files in one zip you can archive this in 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'
这篇关于如何在HttpResponse Django中返回多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!