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 开发者_JS百科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
?
I think this is an issue with whatever you are using to extract the zip. The permissions seem fine to me:
zk@fool:~/Downloads% ls -l | grep thefile
-rwxr-xr-x@ 1 zk staff 9 May 3 06:37 thefile.txt*
Works fine for me with Archive Utility on osx and window's built-in zip explorer and 7-zip. Inspecting the generated zip shows files have no attributes at all. So I suspect whatever you are using to unzip the file is just setting permissions incorrectly.
You could try setting ZipInfo.external_attr:
zipInfo.external_attr = 0777 << 16L # set permissions on file
seems to fix the permissions on a linux system:
zk@arch:~% ls -l | grep thefile
-rwxrwxrwx 1 zk 9 May 3 07:06 thefile.txt*
In unix every process have default file permissions mask.. read on:
umask
try setting it for django process.
精彩评论