I'm using Django and Python2.6 to generate a zip file of custom-rendered Django templates for each user to download a custom-made zip
file. At the moment, the code in views.py
looks like this:
def download(request):
response = HttpResponse(mimetype='application/x-zip-compressed')
response['Content-Disposition'] = 'attachment; filename=download.zip'
myzip = zipfile.ZipFile(response, 'w')
now = datetime.datetime.now()
zipInfo = zipfile.ZipInfo('thefile.txt', (now.year, now.month, now.day, now.hour, now.minute, now.second))
myzip.writestr(zipInfo, render_to_string('template.txt', locals(), context_instance=RequestContext(request)))
myzip.close()
return response
Mostly, this works fine: the zip file (containing a single txt
file in this example) is downloaded correctly, and I can extract the contents. The only problem is, however, that the permissions on the generated file are neither read
nor write
for my default user, and neither will it be for my website users.
How do I change the permissions of the auto-generated file before download?
Update:
I've tried using os.chmod
and os.fchmod
, as suggested by Mike, but this either requires a path name (which I don't have) or gives an error (for fchmod
):
ZipFile instance has no attribute '__trunc__'
One option, I guess, would be to save the zip file first, setting the permissions, and then allowing download, but that seems like overkill - there must be a better way to overcome this simple problem. Anyone have any suggestions or ideas?
Update2:
It seems this issue is limited to Unix systems, as it works fine in Windows and (apparently) OS X. There's a similar thread I found here. As far as I can tell, it must be related to the writestr
method. How do I set the permissions on a file added to a zip file with writestr
?