当前位置:Gxlcms > Python > Python编写一个优美的下载器

Python编写一个优美的下载器

时间:2021-07-01 10:21:17 帮助过:104人阅读

这篇文章主要教大家如何使用Python编写一个优美的下载器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Python编写下载器的具体代码,供大家参考,具体内容如下

  1. #!/bin/python3
  2. # author: lidawei
  3. # create: 2016-07-11
  4. # version: 1.0
  5. # 功能说明:
  6. # 从指定的URL将文件取回本地
  7. #####################################################
  8. import http.client
  9. import os
  10. import threading
  11. import time
  12. import logging
  13. import unittest
  14. from queue import Queue
  15. from urllib.parse import urlparse
  16. logging.basicConfig(level = logging.DEBUG,
  17. format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
  18. datefmt = '%a, %d %b %Y %H:%M:%S',
  19. filename = 'Downloader_%s.log' % (time.strftime('%Y-%m-%d')),
  20. filemode = 'a')
  21. class Downloader(object):
  22. '''''文件下载器'''
  23. url = ''
  24. filename = ''
  25. def __init__(self, full_url_str, filename):
  26. '''''初始化'''
  27. self.url = urlparse(full_url_str)
  28. self.filename = filename
  29. def download(self):
  30. '''''执行下载,返回True或False'''
  31. if self.url == '' or self.url == None or self.filename == '' or self.filename == None:
  32. logging.error('Invalid parameter for Downloader')
  33. return False
  34. successed = False
  35. conn = None
  36. if self.url.scheme == 'https':
  37. conn = http.client.HTTPSConnection(self.url.netloc)
  38. else:
  39. conn = http.client.HTTPConnection(self.url.netloc)
  40. conn.request('GET', self.url.path)
  41. response = conn.getresponse()
  42. if response.status == 200:
  43. total_size = response.getheader('Content-Length')
  44. total_size = (int)(total_size)
  45. if total_size > 0:
  46. finished_size = 0
  47. file = open(self.filename, 'wb')
  48. if file:
  49. progress = Progress()
  50. progress.start()
  51. while not response.closed:
  52. buffers = response.read(1024)
  53. file.write(buffers)
  54. finished_size += len(buffers)
  55. progress.update(finished_size, total_size)
  56. if finished_size >= total_size:
  57. break
  58. # ... end while statment
  59. file.close()
  60. progress.stop()
  61. progress.join()
  62. else:
  63. logging.error('Create local file %s failed' % (self.filename))
  64. # ... end if statment
  65. else:
  66. logging.error('Request file %s size failed' % (self.filename))
  67. # ... end if statment
  68. else:
  69. logging.error('HTTP/HTTPS request failed, status code:%d' % (response.status))
  70. # ... end if statment
  71. conn.close()
  72. return successed
  73. # ... end download() method
  74. # ... end Downloader class
  75. class DataWriter(threading.Thread):
  76. filename = ''
  77. data_dict = {'offset' : 0, 'buffers_byte' : b''}
  78. queue = Queue(128)
  79. __stop = False
  80. def __init__(self, filename):
  81. self.filename = filename
  82. threading.Thread.__init__(self)
  83. #Override
  84. def run(self):
  85. while not self.__stop:
  86. self.queue.get(True, 1)
  87. def put_data(data_dict):
  88. '''''将data_dict的数据放入队列,data_dict是一个字典,有两个元素:offset是偏移量,buffers_byte是二进制字节串'''
  89. self.queue.put(data_dict)
  90. def stop(self):
  91. self.__stop = True
  92. class Progress(threading.Thread):
  93. interval = 1
  94. total_size = 0
  95. finished_size = 0
  96. old_size = 0
  97. __stop = False
  98. def __init__(self, interval = 0.5):
  99. self.interval = interval
  100. threading.Thread.__init__(self)
  101. #Override
  102. def run(self):
  103. # logging.info(' Total Finished Percent Speed')
  104. print(' Total Finished Percent Speed')
  105. while not self.__stop:
  106. time.sleep(self.interval)
  107. if self.total_size > 0:
  108. percent = self.finished_size / self.total_size * 100
  109. speed = (self.finished_size - self.old_size) / self.interval
  110. msg = '%12d %12d %10.2f%% %12d' % (self.total_size, self.finished_size, percent, speed)
  111. # logging.info(msg)
  112. print(msg)
  113. self.old_size = self.finished_size
  114. else:
  115. logging.error('Total size is zero')
  116. # ... end while statment
  117. # ... end run() method
  118. def stop(self):
  119. self.__stop = True
  120. def update(self, finished_size, total_size):
  121. self.finished_size = finished_size
  122. self.total_size = total_size
  123. class TestDownloaderFunctions(unittest.TestCase):
  124. def setUp(self):
  125. print('setUp')
  126. def test_download(self):
  127. url = 'http://dldir1.qq.com/qqfile/qq/QQ8.4/18376/QQ8.4.exe'
  128. filename = 'QQ8.4.exe'
  129. dl = Downloader(url, filename)
  130. dl.download()
  131. def tearDown(self):
  132. print('tearDown')
  133. if __name__ == '__main__':
  134. unittest.main()

这是测试结果:

相关推荐:

Python编写简单网络爬虫抓取视频

以上就是Python编写一个优美的下载器的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行