Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resume file download in Python?

Tags:

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() 

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

like image 790
Stacked Avatar asked Apr 06 '14 12:04

Stacked


People also ask

How do I stop a python download?

You can simply cancel the program itself, by hitting CTRL+C on your keyboard; but if you want something more complicated than that you need to provide more details on how you are running the code.


1 Answers

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) 
like image 122
Piotr Dabkowski Avatar answered Oct 16 '22 00:10

Piotr Dabkowski