从虚拟机下载存档文件需要花费太多时间才能完成

2024-04-24 16:52:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python编写了一个程序,从虚拟机下载.tar.gz归档文件。下载工作正常,但问题是启动时间太长。以下是我处理下载的部分代码:

import os
from wsgiref.util import request_uri
from wsgiref.simple_server import make_server

def download(self,dirr):
     file_url = os.environ['location'] + dirr
     headers = [('Content-Description', 'File Transfer'),
               ('Content-Type', 'application/octet-stream'),
               ('Content-Disposition', 'attachement; filename="'+os.path.basename(file_url)+'"'),
               ('Expires', '0'),
               ('Cache-Control', 'must-revalidate'),
               ('Pragma', 'public'),
               ('Content-Length', str(os.stat(file_url).st_size))]

      file_download = open(file_url, 'rb')
      return headers, file_download.read()

def server_app(environ, start_response):
    crt_handler = handler(request_uri(environ))
    headers, response_body = crt_handler.get() // this calls my download function, which is part of a class. 
    status = '200 OK'
    start_response(status, headers)
    return [response_body] 

def start_server():
   httpd = make_server("", PORT, server_app)
   httpd.serve_forever()

很抱歉,如果我的代码中有些东西没有意义,我只粘贴了进行下载的部分。这个项目做的更多。无论如何,有没有可能让下载速度更快


Tags: 代码fromimporturlserverosresponsedownload
1条回答
网友
1楼 · 发布于 2024-04-24 16:52:14

file_download.read()看起来不对。大多数HTTP库都支持从文件对象进行流式传输

如果make_serverwsgiref.simple_server.make_server,下面的方法可能有效,但我无法测试它。其思想是不直接调用read文件,而是使用wsgiref.util.FileWrapper将其转换为块迭代器。然后从app函数返回迭代器

def download(self,dirr):
     file_url = os.environ['location'] + dirr
     headers = [('Content-Description', 'File Transfer'),
               ('Content-Type', 'application/octet-stream'),
               ('Content-Disposition', 'attachement; filename="'+os.path.basename(file_url)+'"'),
               ('Expires', '0'),
               ('Cache-Control', 'must-revalidate'),
               ('Pragma', 'public'),
               ('Content-Length', str(os.stat(file_url).st_size))]

      file_download = open(file_url, 'rb')
      return headers, wsgiref.util.FileWrapper(file_download) # ***

def server_app(environ, start_response):
    crt_handler = handler(request_uri(environ))
    headers, response_body = crt_handler.get() // this calls my download function, which is part of a class. 
    status = '200 OK'
    start_response(status, headers)
    return response_body # ***

def start_server():
   httpd = make_server("", PORT, server_app)
   httpd.serve_forever()

注意上面有两个变化。以# ***为标志

相关问题 更多 >