tornado异步客户端(callback)
2015-10-10 00:00
295 查看
摘要: 一步一步理解异步概念
tornado官方提供了一个不完整的代码, 这里将代码填充完整以便理解.
样例代码:
输出结果:
通过输出结果可以看得出来, 两次asynchronous_fetch的两用, 仅输出了自己的函数名称, 但是没有输出html内容.
也就是说, 不启用tornado的事件环回机制是不会调用异步代码的.
再次贴上一样的代码(但是在最后一行启用了tornado的事件环回机制).
输出结果:
太多了,就不列出来了.
参考: <http://www.tornadoweb.org/en/stable/guide/async.html#examples>
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>
相关文章推荐
- tornado异步客户端(Future)
- tornado异步客户端(gen.coroutine)
- Intellij idea 不能识别 @Slf4j,@Getter ,@Setter注解,编译通过
- 你的下拉刷新是否“抖”了一下
- 关于PHP中浏览器禁止Cookie后,Session是否能继续使用
- Failed to load VMMR0.r0
- 事件循环和模式
- 异常处理
- 事件
- Http客户端
- 中文乱码
- UIViewController的edgesForExtendedLayout属性
- Git 命令笔记
- 使用Intellij IDEA 进行代码重构
- 使用xpath取得节点的text
- web服务监控邮件告警python程序
- 使用keepalived实现双机热备
- 使用keepalived打造redis双机热备
- 使用keepalived 实现redis主从高可用
- keepalived工作原理和配置说明