我在這個問題上一直在絞盡腦汁。 django有沒有一種方法可以從一個HttpResponse服務多個文件?如何在HttpResponse中返回多個文件Django
我有一個場景,我正在循環瀏覽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文件作爲回報將打破循環。有沒有更簡單的方法來將所有這些附加到單個響應對象中,並返回外部循環並將多個文件中的所有json下載到列表中?
我通過一種方式將所有這些文件封裝到一個zip文件中,但我沒有這樣做,因爲我可以找到的所有例子都帶有路徑和名稱的文件,在這種情況下我沒有這些文件。
UPDATE:
我試圖整合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))
不是這樣做的方式。如果有人能幫助我,我將不勝感激。
你tryed在字典存儲和返回字典? – Zartch
對不起,沒有得到你。我已經有我想從我的視圖下載文件的字典列表。我基本上選擇了管理視圖上的對象列表,然後調用另一個方法(從動作)來獲取我需要返回的json提取列表。 –