【问题标题】:Return file from python module从 python 模块返回文件
【发布时间】:2010-09-26 00:35:42
【问题描述】:

编辑:如何通过 web 服务器从 python 控制器(后端)返回/提供文件,使用 file_name?正如@JV 建议的那样

【问题讨论】:

  • 我猜这个问题不完整。你的意思是通过网络服务器从 python 控制器(后端)返回/提供文件,并设置正确的 mime 类型和名称?
  • 这几乎与 Python 无关。这是一个关于 HTTP 返回类型的问题。如何设置返回类型取决于您的 Web 服务器。你用的是什么网络服务器框架?
  • @S.lott - 我正在使用cherrypy。我如何发送带有cherrypy响应的文件名?
  • 请用所有事实更新问题,包括您当前正在使用但不起作用的代码的 sn-p。

标签: python file mime-types download


【解决方案1】:

有关 MIME 类型的信息(下载方式),请从此处开始:Properly Configure Server MIME Types。

有关 CherryPy 的信息,请查看 Response 对象的属性。您可以设置响应的content type。另外,您可以使用tools.response_headers 设置内容类型。

当然,还有File Download 的例子。

【解决方案2】:

CherryPy 完全支持使用

from cherrypy.lib.static import serve_file

如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)

【讨论】:

  • Download 类的缩进关闭。返回不在index方法下且使用8个空格与其他地方使用的4个空格不一致。
【解决方案3】:

您可以传回对文件本身的引用,即文件的完整路径。然后您可以打开文件或以其他方式对其进行操作。

或者,更正常的情况是传回文件句柄,并对文件句柄使用标准的读/写操作。

不建议传递实际数据,因为文件可以任意大,程序可能会耗尽内存。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    相关资源
    最近更新 更多