从Python模块返回文件

1 投票
3 回答
18250 浏览
提问于 2025-04-11 20:19

编辑:如何通过一个Python控制器(后端)在网络服务器上返回/提供一个文件,并且带上文件名?这是@JV建议的。

3 个回答

0

如果你想了解MIME类型(这就是下载文件时用到的东西),可以从这里开始:正确配置服务器的MIME类型

关于CherryPy的信息,可以看看Response对象的属性。你可以设置响应的内容类型。另外,你还可以使用tools.response_headers来设置内容类型。

当然,还有一个关于文件下载的例子。

2

你可以选择返回文件本身的引用,也就是文件的完整路径。这样你就可以打开这个文件或者对它进行其他操作。

更常见的做法是返回文件句柄,然后使用标准的读写操作来处理这个文件句柄。

不建议直接传递实际的数据,因为文件可能非常大,程序可能会耗尽内存。

在你的情况下,你可能想返回一个包含打开的文件句柄、文件名和你感兴趣的其他元数据的元组。

1

在CherryPy中完全支持这个功能,使用方法如下:

from cherrypy.lib.static import serve_file

具体的说明可以在CherryPy文档 - 文件下载中找到:

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)

撰写回答