tornado官方提供了一个不完整的代码, 这里将代码填充完整以便理解.
样例代码:
# -.- coding:utf-8 -.-
# __author__ = 'zt'
import tornado.ioloop
from tornado.httpclient import AsyncHTTPClient
# 定义函数: 处理html内容
def read_content(html):
print html
# 定义函数: 获取html内容
def asynchronous_fetch(url, callback):
# 实例化一个异步的http客户端
# 该客户端支持调用外部方法来处理结果.
http_client = AsyncHTTPClient()
# 定义函数: 将内容交给callback处理.
def handle_response(response):
callback(response.body)
# 获取url网址的html内容, 并通过callback丢给handle_response函数
http_client.fetch(url, callback=handle_response)
# 打印函数名称
print sys._getframe().f_code.co_name
if __name__ == '__main__':
# 调用函数asynchronous_fetch时,仅执行asynchronous_fetch函数里面的代码(默认不会帮你执行callback的代码)
# 只有启动tornado的事件环回机制后<tornado.ioloop.IOLoop.instance().start()>
# 才会执行callback中的内容.
asynchronous_fetch(url='http://www.qq.com', callback=read_content)
asynchronous_fetch(url='http://www.qq.com', callback=read_content)
输出结果:
asynchronous_fetch
asynchronous_fetch
通过输出结果可以看得出来, 两次asynchronous_fetch的两用, 仅输出了自己的函数名称, 但是没有输出html内容.
也就是说, 不启用tornado的事件环回机制是不会调用异步代码的.
再次贴上一样的代码(但是在最后一行启用了tornado的事件环回机制).
# -.- coding:utf-8 -.-
# __author__ = 'zt'
import tornado.ioloop
from tornado.httpclient import AsyncHTTPClient
# 定义函数: 处理html内容
def read_content(html):
print html
# 定义函数: 获取html内容
def asynchronous_fetch(url, callback):
# 实例化一个异步的http客户端
# 该客户端支持调用外部方法来处理结果.
http_client = AsyncHTTPClient()
# 定义函数: 将内容交给callback处理.
def handle_response(response):
callback(response.body)
# 获取url网址的html内容, 并通过callback丢给handle_response函数
http_client.fetch(url, callback=handle_response)
# 打印函数名称
print sys._getframe().f_code.co_name
if __name__ == '__main__':
# 调用函数asynchronous_fetch时,仅执行asynchronous_fetch函数里面的代码(默认不会帮你执行callback的代码)
# 只有启动tornado的事件环回机制后<tornado.ioloop.IOLoop.instance().start()>
# 才会执行callback中的内容.
asynchronous_fetch(url='http://www.qq.com', callback=read_content)
asynchronous_fetch(url='http://www.qq.com', callback=read_content)
tornado.ioloop.IOLoop.instance().start()
输出结果:
太多了,就不列出来了.
参考: <http://www.tornadoweb.org/en/stable/guide/async.html#examples>