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

cfi*_*her 2 python performance cgi 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)
Run Code Online (Sandbox Code Playgroud)

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

任何帮助是极大的赞赏.

Gra*_*ton 9

使用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)
Run Code Online (Sandbox Code Playgroud)

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