Python URL检索限制率并恢复部分下载

发布于 2021-01-29 14:59:51

我正在使用此线程中的代码来限制下载速度。

如何合并使用限速代码恢复的部分下载?我发现的示例urlopen代替urlretrieve,而RateLimit类取决于urlretrieve

我想要一个外部函数来控制部分下载,而无需更改RateLimit类:

from throttle import TokenBucket, RateLimit

def retrieve_limit_rate(url, filename, rate_limit):
    """Fetch the contents of urls"""
    bucket = TokenBucket(10*rate_limit, rate_limit)

    print "rate limit = %.1f kB/s" % (rate_limit,)

    print 'Downloading %s...' % filename
    rate_limiter = RateLimit(bucket, filename)
    #
    # What do I put here to allow resuming files?
    #
    return urllib.urlretrieve(url, filename, rate_limiter)
关注者
0
被浏览
132
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    也许可以使用PyCurl代替:

    def curl_progress(total, existing, upload_t, upload_d):
        try:
            frac = float(existing)/float(total)
        except:
            frac = 0
        print "Downloaded %d/%d (%0.2f%%)" % (existing, total, frac)
    
    def curl_limit_rate(url, filename, rate_limit):
        """Rate limit in bytes"""
        import pycurl
        c = pycurl.Curl()
        c.setopt(c.URL, url)
        c.setopt(c.MAX_RECV_SPEED_LARGE, rate_limit)
        if os.path.exists(filename):
            file_id = open(filename, "ab")
            c.setopt(c.RESUME_FROM, os.path.getsize(filename))
        else:
            file_id = open(filename, "wb")
    
        c.setopt(c.WRITEDATA, file_id)
        c.setopt(c.NOPROGRESS, 0)
        c.setopt(c.PROGRESSFUNCTION, curl_progress)
        c.perform()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看