2017-03-15 827 views
1

我在這個問題上一直在絞盡腦汁。 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))不是這樣做的方式。如果有人能幫助我,我將不勝感激。

+0

你tryed在字典存儲和返回字典? – Zartch

+0

對不起,沒有得到你。我已經有我想從我的視圖下載文件的字典列表。我基本上選擇了管理視圖上的對象列表,然後調用另一個方法(從動作)來獲取我需要返回的json提取列表。 –

回答

0

也許如果你試圖打包在一個壓縮所有文件,你可以在管理歸檔此

喜歡的東西:

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' 
+0

第一條語句應該是'response = HttpResponse(json.dumps(company_json_list),content_type =「application/json」)',因爲company只是company_json_list中的條目。如果是這樣,它沒有讓我收拾它,因爲我得到了ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION錯誤。 –

+0

更新所有視圖和模板。我沒有得到你。 – Zartch

+0

對不起,我更新了我的代碼。它在管理操作中。我希望這說明了這一點,並表示感謝。 –

相關問題