HTTP Download very Big File

前端 未结 4 1274
借酒劲吻你
借酒劲吻你 2021-02-04 07:47

I\'m working at a web application in Python/Twisted.

I want the user to be able to download a very big file (> 100 Mb). I don\'t want to load all the file in memory (of

4条回答
  •  眼角桃花
    2021-02-04 08:04

    Here is an example of downloading files in chunks using urllib2, which you could use from inside of a twisted function call

    import os
    import urllib2
    import math
    
    def downloadChunks(url):
        """Helper to download large files
            the only arg is a url
           this file will go to a temp directory
           the file will also be downloaded
           in chunks and print out how much remains
        """
    
        baseFile = os.path.basename(url)
    
        #move the file to a more uniq path
        os.umask(0002)
        temp_path = "/tmp/"
        try:
            file = os.path.join(temp_path,baseFile)
    
            req = urllib2.urlopen(url)
            total_size = int(req.info().getheader('Content-Length').strip())
            downloaded = 0
            CHUNK = 256 * 10240
            with open(file, 'wb') as fp:
                while True:
                    chunk = req.read(CHUNK)
                    downloaded += len(chunk)
                    print math.floor( (downloaded / total_size) * 100 )
                    if not chunk: break
                    fp.write(chunk)
        except urllib2.HTTPError, e:
            print "HTTP Error:",e.code , url
            return False
        except urllib2.URLError, e:
            print "URL Error:",e.reason , url
            return False
    
        return file
    

提交回复
热议问题