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()会阻塞主程序,直到队列所有的任务都执行完毕