Tornado使用-队列Queue
1.tornado队列的特点
和python标准队列queue相比,tornado的队列Queue支持异步
2.Queue常用方法
Queue.get()
会暂停,直到queue中有元素
Queue.put()
对有最大长度限制的队列,会暂停,直到队列有空闲空间
Queue.task_done()
对每一个get元素,紧接着调用task_done(),表示这个任务执行完毕
Queue.join()
等待,直到所有任务都执行完毕,即所有元素都调用了task_done()
3.示例
给出一个地址http://www.tornadoweb.org/en/stable/,分析页面中所有以这个url为前缀的链接,
并依次访问,解析,直到找出所有的url
#!/usr/bin/env python
import time
from datetime import timedelta
try:
from HTMLParser import HTMLParser
from urlparse import urljoin, urldefrag
except ImportError:
from html.parser import HTMLParser
from urllib.parse import urljoin, urldefrag
from tornado import httpclient, gen, ioloop, queues
base_url = 'http://www.tornadoweb.org/en/stable/'
concurrency = 10
@gen.coroutine
def get_links_from_url(url):
"""Download the page at `url` and parse it for links.
Returned links have had the fragment after `#` removed, and have been made
absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes
'http://www.tornadoweb.org/en/stable/gen.html'.
"""
try:
response = yield httpclient.AsyncHTTPClient().fetch(url)
print('fetched %s' % url)
html = response.body if isinstance(response.body, str) \
else response.body.decode()
urls = [urljoin(url, remove_fragment(new_url))
for new_url in get_links(html)]
except Exception as e:
print('Exception: %s %s' % (e, url))
raise gen.Return([])
raise gen.Return(urls)
def remove_fragment(url):
pure_url, frag = urldefrag(url)
return pure_url
def get_links(html):
class URLSeeker(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.urls = []
def handle_starttag(self, tag, attrs):
href = dict(attrs).get('href')
if href and tag == 'a':
self.urls.append(href)
url_seeker = URLSeeker()
url_seeker.feed(html)
return url_seeker.urls
@gen.coroutine
def main():
q = queues.Queue()
start = time.time()
fetching, fetched = set(), set()
@gen.coroutine
def fetch_url():
current_url = yield q.get()
try:
if current_url in fetching:
return
print('fetching %s' % current_url)
fetching.add(current_url)
urls = yield get_links_from_url(current_url)
fetched.add(current_url)
for new_url in urls:
# Only follow links beneath the base URL
if new_url.startswith(base_url):
yield q.put(new_url)
finally:
q.task_done()
@gen.coroutine
def worker():
while True:
yield fetch_url()
q.put(base_url)
# Start workers, then wait for the work queue to be empty.
for _ in range(concurrency):
worker()
yield q.join(timeout=timedelta(seconds=300))
assert fetching == fetched
print('Done in %d seconds, fetched %s URLs.' % (
time.time() - start, len(fetched)))
if __name__ == '__main__':
import logging
logging.basicConfig()
io_loop = ioloop.IOLoop.current()
io_loop.run_sync(main)
运行结果:
fetching http://www.tornadoweb.org/en/stable/
fetched http://www.tornadoweb.org/en/stable/
......
fetched http://www.tornadoweb.org/en/stable/_modules/index.html
fetched http://www.tornadoweb.org/en/stable/_modules/tornado/util.html
Done in 11 seconds, fetched 122 URLs.
使用yield,当队列有元素时,q.get()会执行
for _ in range(concurrency): worker()
可以大幅提高效率,原因在于get_links_from_url网络IO会占用较多执行时间,多个异步任务可以并行访问网络io,大大提高了效率。
q.join()会阻塞主程序,直到队列所有的任务都执行完毕
Tornado使用-队列Queue的更多相关文章
- Python进阶【第二篇】多线程、消息队列queue
1.Python多线程.多进程 目的提高并发 1.一个应用程序,可以有多进程和多线程 2.默认:单进程,单线程 3.单进程,多线程 IO操作,不占用CPU python的多线程:IO操作,多线程提供并 ...
- Java中的队列Queue,优先级队列PriorityQueue
队列Queue 在java5中新增加了java.util.Queue接口,用以支持队列的常见操作.该接口扩展了java.util.Collection接口. Queue使用时要尽量避免Collecti ...
- jquery 的队列queue
使用示列代码: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www ...
- Windows Azure Service Bus (2) 队列(Queue)入门
<Windows Azure Platform 系列文章目录> Service Bus 队列(Queue) Service Bus的Queue非常适合分布式应用.当使用Service Bu ...
- Windows Azure Service Bus (3) 队列(Queue) 使用VS2013开发Service Bus Queue
<Windows Azure Platform 系列文章目录> 在之前的Azure Service Bus中,我们已经介绍了Service Bus 队列(Queue)的基本概念. 在本章中 ...
- (C#)使用队列(Queue)解决简单的并发问题
(C#)使用队列(Queue)解决简单的并发问题 2015-07-16 13:04 13265人阅读 评论(8) 收藏 举报 分类: Asp.Net(8) 版权声明:本文为博主原创文章,未经博主允 ...
- STL中的单向队列queue
转载自:http://blog.csdn.net/morewindows/article/details/6950917 stl中的queue指单向队列,使用时,包含头文件<queue>. ...
- java09 队列Queue与Deque
队列Queue与Deque. Enumeration Hashtable与Hashtable子类Properties(资源配置文件) 引用类型(强.软.弱.虚)与WeakHashMap Identit ...
- 队列Queue和栈
1.队列Queue是常用的数据结构,可以将队列看成特殊的线性表,队列限制了对线性表的访问方式,只能从线性表的一段添加(offer)元素, 从另一段取出(poll)元素,队列遵循先进先出的原则. 2.J ...
随机推荐
- Dockerfile 构建后端tomcat应用并用shell脚本实现jenkins自动构建
Dockerfile 文件构建docker镜像 FROM centos MAINTAINER zhaoweifeng "zh******tech.cn" ENV LANG en_U ...
- ios 中UIViewController的分类
#import <UIKit/UIKit.h> #define TOPVIEWTAG 0x10000 // 导航栏的图片 @interface UIViewController (Chnb ...
- 【DeepLearning】Exercise:Learning color features with Sparse Autoencoders
Exercise:Learning color features with Sparse Autoencoders 习题链接:Exercise:Learning color features with ...
- 运维人员20道必会iptables面试题
1.详述iptales工作流程以及规则过滤顺序? iptables过滤的规则顺序是由上至下,若出现相同的匹配规则则遵循由上至下的顺序 2.iptables有几个表以及每个表有几个链? Iptables ...
- jquery 滑动取值
JavaScript 滑动条效果 jquery 滚动条插件 仿iphone苹果横行滚动条美化样式商品图片展示
- 关于去哪儿网的UI自动化测试脚本
UI自动化测试Qunar机票搜索场景访问Qunar机票首页http://flight.qunar.com,选择“单程”,输入出发.到达城市,选择today+7日后的日期,点“搜索”,跳转到机票单程搜索 ...
- 使用ant优化android项目编译速度,提高工作效率
1.Android项目编译周期长,编译项目命令取消困难 2.在进行Android项目的编译的同时,Eclipse锁定工作区不能进行修改操作 3.在只进行资源文件的修改时,Eclipse对资源文件的修改 ...
- win7怎么快速截取图片
点击开始--运行或者winkey + r 键直接进入运行. 2 在输入框输入snippingtool,点击确定. 3 这就找到截图工具,如图. END 方法/步骤2 进入c盘--Windows-- ...
- SQLAlchemy(2) -- SQLAlchemy的安装
安装前要先安装好python 1.使用setup.py脚本进行安装C:\> C:\Python27\python.exe .\setup.py installrunning installrun ...
- Linux shell下30个有趣的命令
Tips 原文作者:Víctor López Ferrando 原文地址:30 interesting commands for the Linux shell 这些是我收集了多年的Linux she ...