I need to create a temporary file to send it, I have tried :
# Create a temporary file --> I think it is ok (file not seen)
temporaryfile = NamedTemporaryFile(delete=False, dir=COMPRESSED_ROOT)
# The path to archive --> It's ok
root_dir = "something"
# Create a compressed file --> It bugs
data = open(f.write(make_archive(f.name, 'zip', root_dir))).read()
# Send the file --> Its ok
response = HttpResponse(data, mimetype='application/zip')
response['Content-Disposition'] = 'attachment; filename="%s"' % unicode(downloadedassignment.name + '.zip')
return response
I don’t know at all if it is the good approach..
First of all, you don’t need to create a
NamedTemporaryFileto usemake_archive; all you want is a unique filename for themake_archivefile to create..writedoesn’t return a filenameTo focus on that error: You are assuming that the return value of
f.writeis a filename you can open; just seek to the start of your file and read instead:Note that you’ll also need to clean up the temporary file you created (you set
delete=False):Alternatively, just omit the
deletekeyword to have it default toTrueagain and only close your file afterwards, no need to unlink.That just wrote the archive filename to a new file..
You are just writing the new archive name to your temporary file. You’d be better off just reading the archive directly:
Note that now your temporary file isn’t being written to at all.
Best way to do this
Avoid creating a
NamedTemporaryFilealtogether: Usetempfile.mkdtemp()instead, to generate a temporary directory in which to put your archive, then clean that up afterwards: