Search code examples
cherrypy

serve arbitrary static content on the fly with cherrypy


I am trying to create a media server using cherrypy and cant get cherrypy to serve up files in any directory that isn't set at startup in the config. I don't want to expose the drives root directory I would prefer to expose a directory at a time as I need it. Is there away to do this?

here is the relevant snippet of my current code.

@cherrypy.expose
def serve_mp3(self, mp3_path):
    #cherrypy.config.update({"media":{
    #"tools.staticdir.on" : True,
    #"tools.staticdir.root" : "C:\\Documents and Settings\\sdc\\My Documents\\My Music",
    #"tools.staticdir.dir" : "",
    #"tools.staticfile.root" : "C:\\Documents and Settings\\sdc\\My Documents\\My Music"
    #}})
    static_handler = cherrypy.tools.staticdir.handler(section="/media", dir="C:\\Documents and Settings\\sdc\\My Documents\\My Music")
    cherrypy.tree.mount(static_handler, '/media')
    mp3 = mp3_path.rsplit("\\",1)[1]
    return "media/" + urllib.quote(mp3)

Thanks go to cyraxjoe the mess above wound up being re-factored as

    @cherrypy.expose
    def serve_mp3(self, mp3_path):
      mp3_path = urllib.unquote(mp3_path)
      return(cherrypy.lib.static.serve_file(mp3_path, content_type="audio/mpeg", disposition=None, name=None))

which worked just fine for serving an audio tag. I know as it exists this is basically front door access to my hdd but this is just a first step and the final result will be driven by a data base


Solution

  • I think that you should use the functions to serve static files directly instead of the handler, you are fighting with the tool. With the direct call of the functions you can serve any arbitrary path or file object if you like.