我有这个 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/