1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| import threading from urllib.request import *
class Download: def __init__(self, link, file_path, thread_num): self.link = link self.file_path = file_path self.thread_num = thread_num self.threads = []
def download(self): req = Request(url=self.link, method='GET') req.add_header('Accept', '*/*') req.add_header('Charset', 'UTF-8') req.add_header('Connection', 'Keep-Alive') f = urlopen(req) self.file_size = int(dict(f.headers).get('Content-Length', 0)) f.close() current_part_size = self.file_size // self.thread_num + 1 for i in range(self.thread_num): start_pos = i * current_part_size t = open(self.file_path, 'wb') t.seek(start_pos, 0) td = ThreadDownload(self.link, start_pos, current_part_size, t) self.threads.append(td) td.start()
def get_complete_rate(self): sum_size = 0 for i in range(self.thread_num): sum_size += self.threads[i].length return sum_size / self.file_size
class ThreadDownload(threading.Thread): def __init__(self, link, start_pos, current_part_size, current_part): super().__init__() self.link = link self.start_pos = start_pos self.current_part_size = current_part_size self.current_part = current_part self.length = 0 def run(self): req = Request(url = self.link, method='GET') req.add_header('Accept', '*/*') req.add_header('Charset', 'UTF-8') req.add_header('Connection', 'Keep-Alive')
f = urlopen(req) for i in range(self.start_pos): f.read(1) while self.length < self.current_part_size: data = f.read(1024) if data is None or len(data) <= 0: break self.current_part.write(data) self.length += len(data) self.current_part.close() f.close()
|