tornado实现python异步

这是facebook开发的一个异步调用库。gevent是future的模式,而tornado则是callback的那种形式。在其他语言比如java中,future本身就是一个实现好的接口,取值只需要调用get()获取返回然后再用框架比如Spring等等实现注入即可,而callback则预先需要定义好返回的结构体。在python中没有这个问题,因为是动态语言,返回的结果是可以即时的使用和处理的。
而且这个包设计得很巧妙,很多地方直接用装饰器一笔带过,而且本身是包含httpClient的,所以主要用于做客户端和服务器间的交互。
而gevent比较底层,只是包含了异步调用的实现,具体做什么依赖自己的开发
也用爬虫为例子,生成url的函数照旧
python用gevent实现异步

from tornado.httpclient import AsyncHTTPClient
from tornado import gen
from tornado import ioloop
from functools import partial

AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient",max_clients=100) #配置HTTP客户端和批量请求进程数

@gen.coroutine
def run(url_tmpl, num_iter=500):
    http_client = AsyncHTTPClient()
    urls = generate_ruls(url_tmpl, num_iter)
    responses = yield [http_client.fetch(url) for url in urls]
    # 写方法遍历处理responses,会在异步调用完成后继续执行处理方法产生result
    raise gen.Return(result) #因为tornado的协程由python generators产生,为了返回,需要产生特殊异常,让@gen.coroutine去捕捉形成返回值

_ioloop = ioloop.iollop.IOLoop.instance
run_func = partial(run, url_tmpl, num_iter)
result = _iollp.run_sync(run_func)

猜你喜欢

转载自blog.csdn.net/weixin_41571449/article/details/80157620