Reputation: 1419
In cherrypy.lib.static.py there is a method:
serve_file(path, content_type=None, disposition=None, name=None)
where the argument "path" must be a real file (absolute path). Is there something similar to serve any Python file object?
Upvotes: 1
Views: 2980
Reputation: 14559
As long as your file or file-like object is iterable, just return it from your handler function instead of a string.
Update:
To serve it as a download, set the Content-Type and Content-Disposition headers like so:
cherrypy.response.headers["Content-Type"] = "application/x-download"
cd = 'attachment; filename="%s"' % name
cherrypy.response.headers["Content-Disposition"] = cd
Or, use the serve_fileobj
function in recent versions of cherrypy/lib/static.py
, which does this for you and more.
Upvotes: 2
Reputation: 59405
Taking a new look at http://www.cherrypy.org/browser/trunk/cherrypy/lib/static.py, it looks like serve_fileobj
does exactly what you want.
Edit: I've tried this now, and it only renders the file contents to the screen, rather than allowing the file to be downloaded.
Upvotes: 0
Reputation: 882691
From studying http://www.cherrypy.org/browser/trunk/cherrypy/lib/static.py I'd have to say, no: the serve_file
function is "monolithic", and does its own bodyfile = open(path, 'rb')
, nor does there seem to be any alternative way. Pity, as it would be easy to refactor the function and add another e.g. serve_open_file
to cover your case, having both delegate to an internal function for the "hard" logic such as multipart/byteranges serving. May be worth your while to open a feature request ("enhancement ticket") on cherrypy.org -- may not be a killer feature but I can see use cases, and implementing it wouldn't be hard for the cherrypy people (visit their site and follow the instructions on the page to "log in" to it).
Upvotes: 3