I would like to generate a password-protected Zip file for my csv data in memory and return to webpage via Django HttpResponse. So far I can generate plain zip file to HttpResponse as follows:
from django.http import HttpResponse
import io, csv, zipfile, subprocess
#...
# write csv in buffer
buffer_string_csv = io.StringIO()
writer = csv.writer(buffer_string_csv)
writer.writerow(['foo','bar'])
# write zip in buffer
buffer_zip = io.BytesIO()
zip_file = zipfile.ZipFile(buffer_zip, 'w')
zip_file.writestr('foobar.csv', buffer_string_csv.getvalue())
zip_file.close()
# return zip file as response
response = HttpResponse(buffer_zip.getvalue())
response['Content-Type'] = 'application/x-zip-compressed'
response['Content-Disposition'] = 'attachment; filename="foobar.zip"'
return response
The problem is the password-protecting part for the Zip file.
From this question, I learned password-protecting Zip file can be created via 7-Zip utility.
subprocess.run(['7z', 'a', '-pPASSWORD', '-y', 'password_foobar.zip'] + ['foobar.csv'])
Is it possible to do that in-memory?
Or any alternatives that don't require saving intermediate files into the filesystem?