tornado异步客户端(callback)

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>

转载于:https://my.oschina.net/zhengtong0898/blog/515092

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值