views:

523

answers:

3

Edit: How to return/serve a file from a python controller (back end) over a web server, with the file_name? as suggested by @JV

+2  A: 

You can either pass back a reference to the file itself i.e. the full path to the file. Then you can open the file or otherwise manipulate it.

Or, the more normal case is to pass back the file handle, and, use the standard read/write operations on the file handle.

It is not recommended to pass the actual data as files can be arbiterally large and the program could run out of memory.

In your case, you probably want to return a tuple containing the open file handle, the file name and any other meta data you are interested in.

James Anderson
A: 

For information on MIME types (which are how downloads happen), start here: Properly Configure Server MIME Types.

For information on CherryPy, look at the attributes of a Response object. You can set the content type of the response. Also, you can use tools.response_headers to set the content type.

And, of course, there's an example of File Download.

S.Lott
just correcting the link (typo)fromhttp://https//developer.mozilla.org/en/Properly_Configuring_Server_MIME_Typestohttps://developer.mozilla.org/en/Properly_Configuring_Server_MIME_Types
JV
+1  A: 

Fully supported in CherryPy using

from cherrypy.lib.static import serve_file

As documented in the CherryPy docs - FileDownload:

import glob
import os.path

import cherrypy
from cherrypy.lib.static import serve_file


class Root:
    def index(self, directory="."):
        html = """<html><body><h2>Here are the files in the selected directory:</h2>
        <a href="index?directory=%s">Up</a><br />
        """ % os.path.dirname(os.path.abspath(directory))

        for filename in glob.glob(directory + '/*'):
            absPath = os.path.abspath(filename)
            if os.path.isdir(absPath):
                html += '<a href="/index?directory=' + absPath + '">' + os.path.basename(filename) + "</a> <br />"
            else:
                html += '<a href="/download/?filepath=' + absPath + '">' + os.path.basename(filename) + "</a> <br />"

        html += """</body></html>"""
        return html
    index.exposed = True

class Download:
        def index(self, filepath):
        return serve_file(filepath, "application/x-download", "attachment")
        index.exposed = True

if __name__ == '__main__':
    root = Root()
    root.download = Download()
    cherrypy.quickstart(root)
gimel