Query示例-并发网络蜘蛛
Tornado 的tornado.queues模块为协程实现了异步生产者/消费者模式,类似于 Python 标准库的queue模块为线程实现的模式。
产生Queue.get暂停的协程直到队列中有一个项目。如果队列设置了最大大小,则产生的协程会Queue.put暂停,直到有空间容纳另一个项目。
一个Queue维护未完成任务的计数,该计数从零开始。 put增加计数;task_done递减它。
在此处的 web-spider 示例中,队列开始时仅包含 base_url。当工作人员获取页面时,它会解析链接并将新链接放入队列中,然后调用task_done以减少计数器一次。最终,一个工作人员获取了一个之前所有 URL 都已看到的页面,并且队列中也没有剩余工作。因此,该工人的调用task_done 将计数器减至零。正在等待加入的主协同程序未暂停并完成。
#!/usr/bin/env python3
import time
from datetime import timedelta
from html.parser import HTMLParser
from urllib.parse import urljoin, urldefrag
from tornado import gen, httpclient, ioloop, queues
base_url = "http://www.tornadoweb.org/en/stable/"
concurrency = 10
async 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".
"""
response = await httpclient.AsyncHTTPClient().fetch(url)
print("fetched %s" % url)
html = response.body.decode(errors="ignore")
return [urljoin(url, remove_fragment(new_url)) for new_url in get_links(html)]
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
async def main():
q = queues.Queue()
start = time.time()
fetching, fetched, dead = set(), set(), set()
async def fetch_url(current_url):
if current_url in fetching:
return
print("fetching %s" % current_url)
fetching.add(current_url)
urls = await 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):
await q.put(new_url)
async def worker():
async for url in q:
if url is None:
return
try:
await fetch_url(url)
except Exception as e:
print("Exception: %s %s" % (e, url))
dead.add(url)
finally:
q.task_done()
await q.put(base_url)
# Start workers, then wait for the work queue to be empty.
workers = gen.multi([worker() for _ in range(concurrency)])
await q.join(timeout=timedelta(seconds=300))
assert fetching == (fetched | dead)
print("Done in %d seconds, fetched %s URLs." % (time.time() - start, len(fetched)))
print("Unable to fetch %s URLS." % len(dead))
# Signal all the workers to exit.
for _ in range(concurrency):
await q.put(None)
await workers
if __name__ == "__main__":
io_loop = ioloop.IOLoop.current()
io_loop.run_sync(main)
HTML、JSON、URL等转义和tornado.escape.utf8(value:Union[None,str,bytes])→Optional[bytes]取消转义的方法。还包括随着...
声明不属于路径参数的其他函数参数时,它们将被自动解释为"查询字符串"参数from fastapi import FastAPIapp = FastAPI()fake_ite...
既然我们已经有了所有的安全流程,就让我们来使用JWT令牌和安全哈希密码让应用程序真正地安全吧。你可以在应用程序中真正地使用...
要定义多对多关系,请使用ManyToManyField。在这个例子中,一个Article可以在多个Publication对象中发布,而一个P...