python壓縮文件,Django下載zip文件

python壓縮文件

  • 使用zipfile

    import zipfile
    def convert_zip(zip_path, save_path):
        '''
        # zip_path 要壓縮文件的路徑
        # save_path 文件壓縮後保存的路徑
        '''
        local_path = os.path.join(zip_path, "x.xls")
        zip = zipfile.ZipFile(save_path, "w")  #  zipfile.ZIP_DEFLATED
        zip.write(local_path, 'x.xls')
        zip.close()
    
    convert_zip(zip_path, save_path)

Django下載zip文件

  • Django使用臨時文件夾tempfile下載其他文件,並壓縮爲zip文件返回給前端
  • 使用BytesIO()tempfile下載

    import io
    def contract_download(download_urls):
        '''
        downloads_urls 要批量下載並且壓縮的文件
        '''
        # 創建BytesIO
        s = io.BytesIO()
        # 創建一個臨時文件夾用來保存下載的文件
        temp = tempfile.TemporaryDirectory()
        # 使用BytesIO生成壓縮文件
        zip = zipfile.ZipFile(s, 'w')
        for i in download_urls:
            f_name = "{}.pdf".format(i['name'])
            local_path = os.path.join(temp.name, f_name)
            # 下載文件
            ur.urlretrieve(i['download_url'], local_path)
            # 把下載文件的寫入壓縮文件
            zip.write(local_path, f_name)
        # 關閉文件
        zip.close()
        # 指針回到初始位置,沒有這一句前端得到的zip文件會損壞
        s.seek(0)
        # 用FileWrapper類來迭代器化一下文件對象,實例化出一個經過更適合大文件下載場景的文件對象,實現原理相當與把內容一點點從文件中讀取,放到內存,下載下來,直到完成整個下載過程。這樣內存就不會擔心你一下子佔用它那麼多空間了。
        wrapper = FileWrapper(s)
        response = HttpResponse(wrapper, content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename={}.zip'.format(datetime.datetime.now().strftime("%Y-%m-%d"))
        return response
    
    download_urls = [{"name":"pdf1","download_url": "http://xxx.pdf"}, {"name":"pdf2", "download_url": "http://xxx2.pdf"}]
    contract_download(download_urls)

參考鏈接:時光不寫博客-Django下載zip文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章