In TurboGears, I had to implement a file download method, but the file required access controls so it was put in a directory not exported by Apache.
#turbogears I've been pointed at:
and this is everything put together:
from cherrypy.lib.cptools import serveFile # In cherrypy 3 it should be: #from cherrypy.lib.static import serve_file @expose() def get(self, *args, **kw): """Access the file pointed by the given path""" pathname = check_auth_and_compute_pathname() return serveFile(pathname)
Then I needed to export some CSV:
@expose() def getcsv(self, *args, **kw): """Get the data in CSV format""" rows = compute_data_rows() headers = compute_headers(rows) filename = compute_file_name() cherrypy.response.headers['Content-Type'] = "application/x-download" cherrypy.response.headers['Content-Disposition'] = 'attachment; filename="'+filename+'"' csvdata = StringIO.StringIO() writer = csv.writer(csvdata) writer.writerow(headers) writer.writerows(rows) return csvdata.getvalue()
In my case it's not an issue as I can only compute the headers after I computed all the data, but I still have to find out how to serve the CSV file while I'm generating it, instead of storing it all into a big string and returning the big string.