Skip to content
Advertisement

How do I zip an entire folder (with subfolders) and serve it through Flask without saving anything to disk

I have a folder structure on my web server that I would like to serve as a zipped archive through Flask.

Serving a file through Flask is pretty straight forward through Flasks send_file:

return send_file(my_file,
                     attachment_filename=fileName,
                     as_attachment=True)

Zipping can get accomplished in various ways like with shutil.make_archive or zipfile, but i cannot figure out how to zip the whole directory in memory and then send it without saving anything to disk. shutil.make_archive seem to only be able to create archives on disk. The examples on zipfile found on the Internet are mainly about serving single files.

How would I tie this together in a single method without having to save everything to disk? Preferably using BytesIO.

Advertisement

Answer

import time
from io import BytesIO
import zipfile
import os
from flask import send_file


@app.route('/zipped_data')
def zipped_data():
    timestr = time.strftime("%Y%m%d-%H%M%S")
    fileName = "my_data_dump_{}.zip".format(timestr)
    memory_file = BytesIO()
    file_path = '/home/data/'
    with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
          for root, dirs, files in os.walk(file_path):
                    for file in files:
                              zipf.write(os.path.join(root, file))
    memory_file.seek(0)
    return send_file(memory_file,
                     attachment_filename=fileName,
                     as_attachment=True)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement