如何在 Python 中恢复文件下载? [英] How to resume file download in Python?

查看:61
本文介绍了如何在 Python 中恢复文件下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python 2.7 requests 模块使用以下代码下载二进制文件,如何使此代码自动恢复"从部分下载的文件中下载.

I am using python 2.7 requests module to download a binary file using the following code, how to make this code "auto-resume" the download from partially downloaded file.

r = requests.get(self.fileurl, stream=True,  verify=False, allow_redirects=True)
if r.status_code == 200:
    CHUNK_SIZE = 8192
    bytes_read = 0
    with open(FileSave, 'wb') as f:
        itrcount=1
        for chunk in r.iter_content(CHUNK_SIZE):
            itrcount=itrcount+1
            f.write(chunk)
            bytes_read += len(chunk)
            total_per = 100 * float(bytes_read)/float(long(audioSize)+long(videoSize))


            self.progress_updates.emit('%d\n%s' % (total_per, 'Download Progress : ' + self.size_human(itrcount*CHUNK_SIZE) + '/' + Total_Size))
r.close()

如果可能,我宁愿只使用 requests 模块来实现这一点.

I would prefer to use only requests module to achieve this if possible.

推荐答案

如果 Web 服务器支持范围请求,那么您可以将 Range 标头添加到您的请求中:

If the web server supports the range request then you can add the Range header to your request:

Range: bytes=StartPos-StopPos

您将收到 StartPos 和 StopPos 之间的部分.如果不知道 StopPos 只需使用:

You will receive the part between StartPos and StopPos. If dont know the StopPos just use:

Range: bytes=StartPos-

所以你的代码是:

def resume_download(fileurl, resume_byte_pos):
    resume_header = {'Range': 'bytes=%d-' % resume_byte_pos}
    return requests.get(fileurl, headers=resume_header, stream=True,  verify=False, allow_redirects=True)

这篇关于如何在 Python 中恢复文件下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆