Python编写一个优美的下载器


Posted in Python onApril 15, 2018

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

#!/bin/python3 
# author: lidawei 
# create: 2016-07-11 
# version: 1.0 
# 功能说明: 
#  从指定的URL将文件取回本地 
##################################################### 
 
import http.client 
import os 
import threading 
import time 
import logging 
import unittest 
from queue import Queue 
from urllib.parse import urlparse 
 
logging.basicConfig(level = logging.DEBUG, 
     format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', 
     datefmt = '%a, %d %b %Y %H:%M:%S', 
     filename = 'Downloader_%s.log' % (time.strftime('%Y-%m-%d')), 
     filemode = 'a') 
 
class Downloader(object): 
 '''''文件下载器''' 
 url = '' 
 filename = '' 
 
 def __init__(self, full_url_str, filename): 
  '''''初始化''' 
  self.url = urlparse(full_url_str) 
  self.filename = filename 
 
 def download(self): 
  '''''执行下载,返回True或False''' 
  if self.url == '' or self.url == None or self.filename == '' or self.filename == None: 
   logging.error('Invalid parameter for Downloader') 
   return False 
 
  successed = False 
  conn = None 
  if self.url.scheme == 'https': 
   conn = http.client.HTTPSConnection(self.url.netloc) 
  else: 
   conn = http.client.HTTPConnection(self.url.netloc) 
  conn.request('GET', self.url.path) 
  response = conn.getresponse() 
  if response.status == 200: 
   total_size = response.getheader('Content-Length') 
   total_size = (int)(total_size) 
   if total_size > 0: 
    finished_size = 0 
    file = open(self.filename, 'wb') 
    if file: 
     progress = Progress() 
     progress.start() 
     while not response.closed: 
      buffers = response.read(1024) 
      file.write(buffers) 
 
      finished_size += len(buffers) 
      progress.update(finished_size, total_size) 
      if finished_size >= total_size: 
       break 
     # ... end while statment 
     file.close() 
     progress.stop() 
     progress.join() 
    else: 
     logging.error('Create local file %s failed' % (self.filename)) 
    # ... end if statment 
   else: 
    logging.error('Request file %s size failed' % (self.filename)) 
   # ... end if statment 
  else: 
   logging.error('HTTP/HTTPS request failed, status code:%d' % (response.status)) 
  # ... end if statment 
  conn.close() 
 
  return successed 
 # ... end download() method 
# ... end Downloader class 
 
class DataWriter(threading.Thread): 
 filename = '' 
 data_dict = {'offset' : 0, 'buffers_byte' : b''} 
 queue = Queue(128) 
 __stop = False 
 
 def __init__(self, filename): 
  self.filename = filename 
  threading.Thread.__init__(self) 
 
 #Override 
 def run(self): 
  while not self.__stop: 
   self.queue.get(True, 1) 
 
 def put_data(data_dict): 
  '''''将data_dict的数据放入队列,data_dict是一个字典,有两个元素:offset是偏移量,buffers_byte是二进制字节串''' 
  self.queue.put(data_dict) 
 
 def stop(self): 
  self.__stop = True 
 
class Progress(threading.Thread): 
 interval = 1 
 total_size = 0 
 finished_size = 0 
 old_size = 0 
 __stop = False 
 
 def __init__(self, interval = 0.5): 
  self.interval = interval 
  threading.Thread.__init__(self) 
 
 #Override 
 def run(self): 
  # logging.info('  Total  Finished  Percent  Speed') 
  print('  Total  Finished  Percent  Speed') 
  while not self.__stop: 
   time.sleep(self.interval) 
   if self.total_size > 0: 
    percent = self.finished_size / self.total_size * 100 
    speed = (self.finished_size - self.old_size) / self.interval 
    msg = '%12d %12d %10.2f%% %12d' % (self.total_size, self.finished_size, percent, speed) 
    # logging.info(msg) 
    print(msg) 
 
    self.old_size = self.finished_size 
   else: 
    logging.error('Total size is zero') 
  # ... end while statment 
 # ... end run() method 
 
 def stop(self): 
  self.__stop = True 
 
 def update(self, finished_size, total_size): 
  self.finished_size = finished_size 
  self.total_size = total_size 
 
class TestDownloaderFunctions(unittest.TestCase): 
 
 def setUp(self): 
  print('setUp') 
 
 def test_download(self): 
  url = 'http://dldir1.qq.com/qqfile/qq/QQ8.4/18376/QQ8.4.exe' 
  filename = 'QQ8.4.exe' 
  dl = Downloader(url, filename) 
  dl.download() 
 
 def tearDown(self): 
  print('tearDown') 
 
if __name__ == '__main__': 
 unittest.main()

这是测试结果:

Python编写一个优美的下载器

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python读写ini文件示例(python读写文件)
Mar 25 Python
使用python实现扫描端口示例
Mar 29 Python
Pyhton中防止SQL注入的方法
Feb 05 Python
python通过线程实现定时器timer的方法
Mar 16 Python
python查看微信好友是否删除自己
Dec 19 Python
Python中py文件引用另一个py文件变量的方法
Apr 29 Python
python学习之hook钩子的原理和使用
Oct 25 Python
Ubuntu+python将nii图像保存成png格式
Jul 18 Python
Django中的用户身份验证示例详解
Aug 07 Python
pandas中的数据去重处理的实现方法
Feb 10 Python
Python读入mnist二进制图像文件并显示实例
Apr 24 Python
python 读取串口数据的示例
Nov 09 Python
python实现音乐下载器
Apr 15 #Python
tensorflow 1.0用CNN进行图像分类
Apr 15 #Python
tensorflow学习笔记之mnist的卷积神经网络实例
Apr 15 #Python
tensorflow学习笔记之简单的神经网络训练和测试
Apr 15 #Python
Pytorch入门之mnist分类实例
Apr 14 #Python
pytorch构建网络模型的4种方法
Apr 13 #Python
Python输入二维数组方法
Apr 13 #Python
You might like
php的urlencode()URL编码函数浅析
2011/08/09 PHP
JS异常处理try..catch语句的作用和实例
2014/05/05 PHP
PHP向socket服务器收发数据的方法
2015/01/24 PHP
Symfony2实现在doctrine中内置数据的方法
2016/02/05 PHP
PHP模块化安装教程
2016/06/01 PHP
jQuery+ajax实现顶一下,踩一下效果
2010/07/17 Javascript
Jquery解析json字符串及json数组的方法
2015/05/29 Javascript
JS实现设置ff与ie元素绝对位置的方法
2016/03/08 Javascript
jQuery禁用快捷键例如禁用F5刷新 禁用右键菜单等的简单实现
2016/08/31 Javascript
js实现HashTable(哈希表)的实例分析
2016/11/21 Javascript
详解JavaScript模块化开发
2016/12/04 Javascript
微信小程序获取用户openId的实现方法
2017/05/23 Javascript
原生JS实现图片无缝滚动方法(附带封装的运动框架)
2017/10/01 Javascript
解决vue+element 键盘回车事件导致页面刷新的问题
2018/08/25 Javascript
解决vue props 拿不到值的问题
2018/09/11 Javascript
详解Vue项目中出现Loading chunk {n} failed问题的解决方法
2018/09/14 Javascript
如何在Vue.js中实现标签页组件详解
2019/01/02 Javascript
vue-cli3跨域配置的简单方法
2019/09/06 Javascript
jquery实现吸顶导航效果
2020/01/08 jQuery
Python实现从百度API获取天气的方法
2015/03/11 Python
状态机的概念和在Python下使用状态机的教程
2015/04/11 Python
详解Python pygame安装过程笔记
2017/06/05 Python
Sanic框架Cookies操作示例
2018/07/17 Python
Python字符串逆序的实现方法【一题多解】
2019/02/18 Python
html特殊符号示例 html特殊字符编码对照表
2014/01/14 HTML / CSS
XD健身器材:Kevlar球、Crossfit健身球
2019/03/26 全球购物
求职推荐信
2013/10/28 职场文书
违纪检讨书2000字
2014/02/08 职场文书
中学生打架检讨书
2014/02/10 职场文书
学校四群教育实施方案
2014/06/12 职场文书
2014国庆黄金周超市促销活动方案
2014/09/21 职场文书
二手房购房意向书
2015/05/09 职场文书
幼儿园大班教育随笔
2015/08/14 职场文书
六年级作文之预言作文
2019/10/25 职场文书
python使用pycharm安装pyqt5以及相关配置
2022/04/22 Python
Python自动操作神器PyAutoGUI的使用教程
2022/06/16 Python