python - 如何提高读取大文件并将其作为下载返回的 python cgi 的性能?

标签 python cgi performance mod-wsgi

我有这个 python cgi 脚本,它检查是否没有从同一 IP 多次访问它,如果一切正常,从磁盘 (11MB) 读取一个大文件,然后将其作为下载返回。

它可以工作,但性能很差。瓶颈似乎是一遍又一遍地读取这个巨大的文件:

def download_demo():
    """
    Returns the demo file
    """

    file = open(FILENAME, 'r')
    buff = file.read()

    print "Content-Type:application/x-download\nContent-Disposition:attachment;filename=%s\nContent-Length:%s\n\n%s" %    (os.path.split(FILENAME)[-1], len(buff), buff)

我怎样才能让它更快?我想到了使用 ram 磁盘来保存文件,但必须有更好的解决方案。使用 mod_wsgi 而不是 cgi 脚本会有帮助吗?我可以将大文件保留在 apache 的内存空间中吗?

非常感谢任何帮助。

最佳答案

使用 mod_wsgi 并使用类似于:

def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World!'

    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)

    file = open('/usr/share/dict/words', 'rb')
    return environ['wsgi.file_wrapper'](file)

换句话说,使用 WSGI 标准的 wsgi.file_wrapper 扩展允许 Apache/mod_wsgi 使用 sendfile/mmap 执行文件内容的优化回复。换句话说,避免您的应用程序甚至需要将文件读入内存。

关于python - 如何提高读取大文件并将其作为下载返回的 python cgi 的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1462330/

相关文章:

java - java和python中的RSA加密给出了不同的加密结果

python - PyQt5:如何从字典项列表生成 QTreeView?

python - 处理具有多个选择选项的表单

Perl CGI 通过网络浏览器下载文件

apache - 为什么Apache将URL解码我的查询字符串?

asp.net - 在服务器而不是数据库中拥有(可能)数千个目录的缺点?

ruby-on-rails - 使用 RubyXL 编写 xlsx 文件需要很长时间且包含大量单元格

python - 连接多列在数据框中包含 NaN

python - 如何编辑 JupyterLab 主题

java - JAXB 保留传递给 Marshaller 的对象