开发者

serving mp3 files from cherrypy

I am using cherrypy as a server. This server gives you ability to download .mp3 files. I am using the following code to make the .mp3 files downloadable. The problem is that the mp3 file that I get after downloading it is a data file which should actually be an mp3 file.

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(fil开发者_开发百科ename) + "</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, "audio/mpeg", "attachment")
    index.exposed = True

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


Try setting up the directory that contains the mp3 files as a static directory. Your cherrypy conf should contain something like this:

    '/directory_with_mp3s': {
        'tools.staticdir.on': True, 
        'tools.staticdir.dir': 'directory_with_mp3s'
}

This will allow you to get rid of the Download class and simply create links to the mp3 files in the html that look like this:

<a href="directory_with_mp3s/somemp3.mp3">some mp3</a>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜