Python implements the download interface (with a progress bar, resumable upload from a breakpoint, multi-threaded multi-task download, etc.)

Development environment:

Windows 7 64th, Python 3.6.2

Implementation function:


The progress bar, the display of download speed and download progress, the download interface of breakpoint resuming (pause and continue the download function), cancel the download and other functions
Python implements the download interface (with a progress bar, resumable upload from a breakpoint, multi-threaded multi-task download, etc.)
.
Python implements the download interface (with a progress bar, resumable upload from a breakpoint, multi-threaded multi-task download, etc.)
Click 'Start Download', you can automatically obtain the download file name and select the storage path, as shown in the figure:
Python implements the download interface (with a progress bar, resumable upload from a breakpoint, multi-threaded multi-task download, etc.)

Key code:

Because the breakpoint resume is to continue appending to the previous file, the open(filename,'ab') mode of opening the file here needs to implement the breakpoint resume
for ab as follows:

headers={'Range': 'bytes=%d-' %os.path.getsize(filename) }
r = requests.get(self.url,stream=True,headers=headers)
with open(filename, 'ab') as code:
    for chunk in r.iter_content(chunk_size=1024): #边下载边存硬盘
        if chunk :
            code.write(chunk)

The code to display the progress bar (display the download progress by changing the value of self.value, the range is 0-100):

from tkinter import ttk
self.value=IntVar()
pb=ttk.Progressbar(self.fm4,length=200,variable=self.value)
pb.grid(row=0,column=1)

Attach the key code to download the file:

import os
import requests
import time
import re
import urllib
class Getfile():  #下载文件
    def __init__(self,url):
        self.url=url
        self.flag=True  #当self.flag=False,暂停或取消下载,也就是结束下载线程
        self.header_flag=False #当为True时,设置header,断点续传
        self.re=requests.head(url,allow_redirects=True,timeout=20)  #运行head方法时重定向
    def getsize(self):
        try:
            self.file_total=int(self.re.headers['Content-Length']) #获取下载文件大小    
            return self.file_total
        except:
            return 0
    def getfilename(self):  #获取默认下载文件名
        if 'Content-Disposition' in self.re.headers:
            n=self.re.headers.get('Content-Disposition').split('name=')[1]
            filename=urllib.parse.unquote(n,encoding='utf8')
        else :
            filename=os.path.basename(self.re.url.split('?')[0])
        if filename=='':
            filename='index.html'
        return filename
    def downfile(self,filename):  #下载文件
        self.headers={}
        self.mode='wb'
        if os.path.exists(filename) and self.header_flag:
            self.headers={'Range': 'bytes=%d-' %os.path.getsize(filename) }
            self.mode='ab'
        self.r = requests.get(self.url,stream=True,headers=self.headers)
        with open(filename, self.mode) as code:
            for chunk in self.r.iter_content(chunk_size=1024): #边下载边存硬盘
                if chunk and self.flag:
                    code.write(chunk)
                else:
                    break
        time.sleep(1)
    def cancel(self,filename):  #取消下载
        self.flag=False
        time.sleep(1)
        if os.path.isfile(filename):
            os.remove(filename)

There is a lot of code to implement the interface, so I won't give it here. All source code has been uploaded to http://down.51cto.com/data/2445977 , you can download it if you need it.

Thinking and Summarizing

It took a lot of time to cancel the download, and I have been entangled in how to force quit the thread that downloads the file. Finally, I found that there is no need to force quit, and directly increase the self.flag flag in the function of downloading the file. When it is false, the thread can be quit. .
This small project has learned more about multithreading.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324660758&siteId=291194637