Return file from python module

Edit: how to return / serve a file from a python controller (back end) via a webserver with a filename? as suggested by @JV

+1


source to share


3 answers


Fully supported in CherryPy with

from cherrypy.lib.static import serve_file

      



As described 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)

      

+1


source


You can either pass a link 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 a file descriptor and use standard read / write operations on the file descriptor.



It is not recommended to transfer the actual data, as the files may be much larger and the program may not work.

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

+2


source


For information on MIME types (as it happens on upload), start here: Configure MIME Server Types Correctly .

For information about CherryPy, see the attributes of the Response object . You can set the content type of the response. Alternatively, you can use tools.response_headers to set the content type.

And of course there is an example Uploading a file .

0


source







All Articles