Create a temporary file with django as a zip file and return it

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 creation 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

Recommended Posts

Create a temporary file with django as a zip file and return it
Create a file uploader with Django
Create and return a CP932 CSV file for Excel with Chalice
Create a homepage with django
Create a deploy script with fabric and cuisine and reuse it
Create a large text file with shellscript
Create a VM with a YAML file (KVM)
Read CSV file with Python and convert it to DataFrame as it is
Create a Todo app with Django ④ Implement folder and task creation functions
Create a decision tree from 0 with Python and understand it (5. Information Entropy)
How to disguise a ZIP file as a PNG file
Create a GUI executable file created with tkinter
Create a PDF file with a random page size
Create a dashboard for Network devices with Django!
Create a one-file hello world application with django
Create a Photoshop format file (.psd) with python
Create a cylinder with open3d + STL file output
Divide each PowerPoint slide into a JPG file and output it with python
I want to write an element to a file with numpy and check it.
Zip-compress any file with the [shell] command to create a file and delete the original file.
Formulate a numberlink-like puzzle as a constraint satisfaction problem and solve it with a constraint solver
Create a Django schedule
Create a Todo app with the Django REST framework
Create a Todo app with Django ③ Create a task list page
Create a batch of images and inflate with ImageDataGenerator
File upload with django
Read json file with Python, format it, and output json
Quickly create a Python data analysis dashboard with Streamlit and deploy it to AWS
Create a 3D model viewer with PyQt5 and PyQtGraph
To myself as a Django beginner (1) --Create a project app--
[Python] Create a Tkinter program distribution file with cx_Freeze
Until you create a machine learning environment with Python on Windows 7 and run it
To myself as a Django beginner (4) --Create a memo app--
Create a Todo app with Django ⑤ Create a task editing function
Create a django environment with docker-compose (MariaDB + Nginx + uWSGI)
Create a 2d CAD file ".dxf" with python [ezdxf]
[Linux] Create a self-signed certificate with Docker and apache
Create an audio file with the text-to-speech function with Google Text To Speak and check the text as a guide for the speech for 3 minutes.
Create a decision tree from 0 with Python and understand it (3. Data analysis library Pandas edition)
When I deploy a Django app with Apache2 and it no longer reads static files
Steps to create a Job that pulls a Docker image and tests it with Github Actions
Steps to set up Pipenv, create a CRUD app with Flask, and containerize it with Docker
[Python] Create a file & folder path specification screen with tkinter
As a result of mounting and tuning with POH! Lite
Create a web surveillance camera with Raspberry Pi and OpenCV
Associate Python Enum with a function and make it Callable
Create applications, register data, and share with a single email
Let's create a PRML diagram with Python, Numpy and matplotlib.
[Django] Create a model suitable for phone numbers / zip codes
Until I return something with a line bot in Django!
Create an authentication feature with django-allauth and CustomUser in Django
Create a web API that can deliver images with Django
Create a Todo app with Django ① Build an environment with Docker
Create a social integration API for smartphone apps with Django
[Python] Create a screen for HTTP status code 403/404/500 with Django
Read and write a file
Create a dummy data file
Create a Django login screen
Create a heatmap with pyqtgraph
Write and read a file
Create and list Django models