How to resume file download in Python?

Posted on

Question :

How to resume file download in Python?

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('%dn%s' % (total_per, 'Download Progress : ' + self.size_human(itrcount*CHUNK_SIZE) + '/' + Total_Size))
r.close()

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

Asked By: Stacked

||

Answer #1:

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

Range: bytes=StartPos-StopPos

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

Range: bytes=StartPos-

So your code would be:

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)
Answered By: Piotr Dabkowski

Leave a Reply

Your email address will not be published.