Reputation: 1409
I'm new to tornado and I need to serve a zip file (made by python).
So i added this code lines to my script, found here:
zipname="clients_counter.zip"
zf = zipfile.ZipFile(zipname, "w")
for dirname, subdirs, files in os.walk("tozip"):
zf.write(dirname)
for filename in files:
zf.write(os.path.join(dirname, filename))
zf.close()
self.set_header('Content-Type', 'application/zip')
self.write(zipname.getvalue())
self.finish()
This just gives me a white page as a result, it doessn't start the download. Does anyone a better advice to accomplish my goal?
Upvotes: 3
Views: 1823
Reputation: 51
If you want to send the zipfile to browser on the fly (without saving to the local filesystem), try this:
from io import BytesIO
zipname="clients_counter.zip"
f=BytesIO()
zf = zipfile.ZipFile(f, "w")
for dirname, subdirs, files in os.walk("tozip"):
zf.write(dirname)
for filename in files:
zf.write(os.path.join(dirname, filename))
zf.close()
self.set_header('Content-Type', 'application/zip')
self.set_header("Content-Disposition", "attachment; filename=%s" % zipname)
self.write(f.getvalue())
f.close()
self.finish()
BytesIO object is where the zipfile goes, and the zipname is just a name sent to client's browser.
Upvotes: 3
Reputation: 1409
I've read a little bit around and this is what I found out: I've built up the directory static for tornado, i've changed the python code to store the zip file inside the static folder:
zipname="C:/whatever/static/clients_counter.zip"
zf = zipfile.ZipFile(zipname, "w")
for dirname, subdirs, files in os.walk("tozip"):
zf.write(dirname)
for filename in files:
zf.write(os.path.join(dirname, filename))
zf.close()
self.write("""<a href="/static/clients_counter.zip"> Download Zip of client counter files</a>""")
except:
traceback.print_exc()
settings = {
"static_path" : os.path.join(os.path.dirname(__file__), "static")
} # This indicates the directory for static files to the server:
# it has to be a directory called static inside the project directory
Much easier than building a new directory or using other more difficult hacks. If this can help anyone, i'm glad.
Upvotes: 0