Skip to content

Instantly share code, notes, and snippets.

@vulcan25
Last active February 29, 2024 13:26
Show Gist options
  • Save vulcan25/563808b415024925d2670b9381aa9763 to your computer and use it in GitHub Desktop.
Save vulcan25/563808b415024925d2670b9381aa9763 to your computer and use it in GitHub Desktop.
Create ZIP file in memory from PIL images and serve with Flask

First do pip install flask Pillow in your venv :)

from flask import Flask, send_file
import memoryzip
app = Flask(__name__)
# This config var saves headaches with CacheControl when developing
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = -1
@app.route('/downloader')
def download():
# Output 4 image files this time:
list_of_tuples = [(f'{i}.png', memoryzip.get_image_buffer(memoryzip.fetch_image()))
for i in range(1,5)]
buff = memoryzip.get_zip_buffer(list_of_tuples)
return send_file(buff,
mimetype='application/zip',
as_attachment=True,
attachment_filename='memoryzip.zip')
import io
import zipfile
from PIL import Image
def fetch_image():
''' mock function to return pil image'''
return Image.new('RGB', (400, 300))
def get_image_buffer(image):
img_buffer = io.BytesIO()
image.save(img_buffer, 'PNG')
img_buffer.seek(0)
return img_buffer
def get_zip_buffer(list_of_tuples):
zip_buffer = io.BytesIO()
# https://stackoverflow.com/a/44946732 <3
with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file:
for file_name, data in list_of_tuples:
zip_file.writestr(file_name, data.read())
zip_buffer.seek(0)
return zip_buffer
if __name__ == '__main__':
# Usage
list_of_tuples = [('1.png', get_image_buffer(fetch_image())),
('2.txt', io.BytesIO(b'i am text'))]
with open('test.zip', 'wb') as f:
f.write(get_zip_buffer(list_of_tuples).getvalue())
@vulcan25
Copy link
Author

When you are trying to serve it via Flask, does that package exist? Its not in the python library nor on pip

Sorry, that's referring to the memoryzip.py module, which is the second file in this gist! You should save this alongside your app.py.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment