tornado

2018-09-27  本文已影响0人  MononokeHime

1.tornado是单进程单线程

image.png
image.png

2.Tornado教程

3.Tornado异步模型

异步模式

Tornado怎么实现异步非阻塞?主要靠下面三个内容

Future类

class Future(object):
   def __init__(self):
        self._done = False
        self._result = None
        self._exc_info = None

        self._log_traceback = False   # Used for Python >= 3.4
        self._tb_logger = None        # Used for Python <= 3.3

        self._callbacks = []

一:异步模型的基本使用

from tornado import gen
from tornado.concurrent import Future

class AsyncHandler(tornado.web.RequestHandler):
 
    @gen.coroutine
    def get(self):
        future = Future()
        future.add_done_callback(self.doing)
        yield future
        # 或
        # tornado.ioloop.IOLoop.current().add_future(future,self.doing)
        # yield future
 
    def doing(self,*args, **kwargs):
        self.write('async')
        self.finish()

二:add_timeout:设置超时时间,时间到了会调用回调函数

class AsyncHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self):
        future = Future()
        tornado.ioloop.IOLoop.current().add_timeout(time.time() + 5, self.doing)
        yield future


    def doing(self, *args, **kwargs):
        self.write('async')
        self.finish()

三:远程异步请求模块--可以用来爬虫

from tornado import gen
from tornado.concurrent import Future
from tornado import httpclient

class AsyncHandler(tornado.web.RequestHandler):
    @gen.coroutine # 这个装饰器使Tornado永远不会自己关闭连接,所以使用finish
    def get(self):
        http = httpclient.AsyncHTTPClient()
        yield http.fetch('http://www.google.com',callback = self.done)  # 内部创建了Future对象,请求结束之后在future的result里写了结果

    def done(self, response):
        self.write(response)
        self.finish()

四:利用Future设置result,使结果返回

import tornado.web
from tornado import gen
from tornado.concurrent import Future
from tornado import httpclient

future = Future()

class AsyncHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self):
        global future
        future.add_done_callback(self.done)
        yield future

    def done(self, *args, **kwargs):
        self.write('async')
        self.finish()


class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        global future
        future.set_result('随便写,目的是让future结束')
        self.write('Index')


if __name__ == '__main__':
    app = tornado.web.Application([(r'/async',AsyncHandler),(r'/index',IndexHandler)])
    app.listen(8080)
    tornado.ioloop.IOLoop.current().start()
上一篇下一篇

猜你喜欢

热点阅读