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:
JavaScript
x
4
1
return send_file(my_file,
2
attachment_filename=fileName,
3
as_attachment=True)
4
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
JavaScript
1
22
22
1
import time
2
from io import BytesIO
3
import zipfile
4
import os
5
from flask import send_file
6
7
8
@app.route('/zipped_data')
9
def zipped_data():
10
timestr = time.strftime("%Y%m%d-%H%M%S")
11
fileName = "my_data_dump_{}.zip".format(timestr)
12
memory_file = BytesIO()
13
file_path = '/home/data/'
14
with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
15
for root, dirs, files in os.walk(file_path):
16
for file in files:
17
zipf.write(os.path.join(root, file))
18
memory_file.seek(0)
19
return send_file(memory_file,
20
attachment_filename=fileName,
21
as_attachment=True)
22