Setting the correct permissions for the generated zip file in Django

I use Django and Python2.6 to create a zip file of custom Django templates for each user to download a custom zip file. Currently, 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 

It basically works just fine: the zip file (containing one txt file in this example) loads correctly and I can extract the contents. The only problem, however, is that the permissions for the generated file are neither read nor write for my user by default, and this will not be for users of my site.

How to change the permissions of an automatically generated file before downloading?

Update:

I tried using os.chmod and os.fchmod , as suggested by Mike, but this requires either a path name (which I don’t have) or an error message (for fchmod ):

ZipFile instance has no attribute '__trunc__'

One option, I think, was to save the zip file first, set permissions, and then allow the download, but this seems like overkill - there should be a better way to overcome this simple problem. Anyone have any suggestions or ideas?

Update2:

This problem seems to be limited to Unix systems, as it works fine on Windows and (apparently) OS X. There is a similar thread that I found here . As far as I can tell, this should be related to the writestr method. How to set permissions for a file added to a zip file using writestr ?

+7
source share
2 answers

I think this is a problem with what you use to extract 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 the archive utility in osx and the built-in window in the zip browser and 7-zip. Checking the created zip files has no attributes. Therefore, I suspect that everything you use to decompress the file is simply setting permissions incorrectly.

You can try setting ZipInfo.external_attr:

 zipInfo.external_attr = 0777 << 16L # set permissions on file 

seems to fix permissions for the linux system:

 zk@arch :~% ls -l | grep thefile -rwxrwxrwx 1 zk 9 May 3 07:06 thefile.txt* 
+4
source

On unix, each process has a default file permissions mask .. read on:
Umask
try installing it for the django process.

0
source

All Articles