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 smtplib模块发送SSL/TLS安全邮件实例
Apr 08 Python
Python实现决策树C4.5算法的示例
May 30 Python
Python对象属性自动更新操作示例
Jun 15 Python
python 读取修改pcap包的例子
Jul 23 Python
使用K.function()调试keras操作
Jun 17 Python
Python日志器使用方法及原理解析
Sep 27 Python
用python实现一个简单计算器(完整DEMO)
Oct 14 Python
解决python3.x安装numpy成功但import出错的问题
Nov 17 Python
python 基于UDP协议套接字通信的实现
Jan 22 Python
教你使用Pandas直接核算Excel中快递费用
May 12 Python
Matplotlib绘制混淆矩阵的实现
May 27 Python
python中的random模块和相关函数详解
Apr 22 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 中include()与require()的对比
2006/10/09 PHP
php 中英文语言转换类
2011/09/07 PHP
php判断文件上传图片格式的实例详解
2017/09/30 PHP
PHP创建对象的六种方式实例总结
2019/06/27 PHP
js获取图片长和宽度的代码
2009/11/24 Javascript
js nextSibling属性和previousSibling属性概述及使用注意
2013/02/16 Javascript
纯js简单日历实现代码
2013/10/05 Javascript
js之ActiveX控件使用说明 new ActiveXObject()
2014/03/03 Javascript
nodejs教程之入门
2014/11/21 NodeJs
Javascript实现网络监测的方法
2015/07/31 Javascript
JavaScript获取当前运行脚本文件所在目录的方法
2016/02/03 Javascript
jQuery简单注册和禁用全局事件的方法
2016/07/25 Javascript
jQuery 局部div刷新和全局刷新方法总结
2016/10/05 Javascript
jQuery实现拖动剪裁图片作为头像
2016/12/28 Javascript
jQuery插件HighCharts实现的2D对数饼图效果示例【附demo源码下载】
2017/03/09 Javascript
Vue.js实战之通过监听滚动事件实现动态锚点
2017/04/04 Javascript
原生js实现移动端触摸轮播的示例代码
2017/12/22 Javascript
微信小程序实现YDUI的ScrollNav组件
2018/02/02 Javascript
微信小程序之onLaunch与onload异步问题详解
2019/03/28 Javascript
python中列表元素连接方法join用法实例
2015/04/07 Python
Python实现的数据结构与算法之链表详解
2015/04/22 Python
Python使用回溯法子集树模板获取最长公共子序列(LCS)的方法
2017/09/08 Python
python 类对象和实例对象动态添加方法(分享)
2017/12/31 Python
使用python 3实现发送邮件功能
2018/06/15 Python
详解pandas使用drop_duplicates去除DataFrame重复项参数
2019/08/01 Python
win10下安装Anaconda的教程(python环境+jupyter_notebook)
2019/10/23 Python
python3实现绘制二维点图
2019/12/04 Python
Python虚拟环境virtualenv创建及使用过程图解
2020/12/08 Python
《赶海》教学反思
2014/04/20 职场文书
课例研修方案
2014/05/31 职场文书
英语专业自荐书
2014/06/13 职场文书
大学生活动总结模板
2014/07/02 职场文书
公司员工违纪检讨书
2015/05/05 职场文书
CSS3通过var()和calc()函数实现动画特效
2021/03/30 HTML / CSS
Python中OpenCV实现简单车牌字符切割
2021/06/11 Python
实体类或对象序列化时,忽略为空属性的操作
2021/06/30 Java/Android