0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

djangoで一時ファイルをzipで作成して返却

Posted at
import tempfile

with tempfile.TemporaryFile() as tmp:
        with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as archive:
                data = []
                count = 1
                for item in (self._iter_csv_rows(
                    queryset=self._get_changelist_instance(request).get_queryset(request),                       charset=charset)):
        data.append(item)
        if len(data) >= 10000:
                        tmp2 = tempfile.TemporaryFile()
                        #csv作成
                        writer = csv.writer(tmp2)
                        writer.writerows(data)
                        tmp2.seek(0)
                        archive.writestr('{}-{}.csv'.format(self.model._meta.model_name,count), tmp2.read())
                        count += 1
                        data = []
                        tmp2.close()

        tmp.seek(0)
        res = HttpResponse(tmp.read(), content_type='application/x-zip-compressed')
        res['Content-Disposition'] = 'attachment; filename={base}_{dt}.zip'.format(
                base=self.model._meta.model_name,
                dt=datetime.now().strftime('%Y%m%d-%H%M%S'))
        res['Pragma'] = 'public'
        res['Cache-Control'] = 'public'

        return res
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?