Tornado 異步非阻塞


1 裝飾器 + Future 從而實現Tornado的異步非阻塞web

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()

當發送GET請求時,因爲方法被@gen.coroutine裝飾且yield 一個 Future對象,那麼Tornado會等待,等待用戶向future對象中放置數據或者發送信號,若是獲取到數據或信號以後,就開始執行doing方法。app

異步非阻塞體如今當在Tornaod等待用戶向future對象中放置數據時,還能夠處理其餘請求。異步

注意:在等待用戶向future對象中放置數據或信號時,此鏈接是不斷開的。async


2 同步阻塞和異步非阻塞tornado

# 同步阻塞

    class SyncHandler(tornado.web.RequestHandler):

        def get(self):
            self.doing()
            self.write('sync')

    # 異步非阻塞

    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()

        def doing(self):
            time.sleep(10)



3 httpclient類庫用於發送Http請求,配合Tornado的異步非阻塞使用oop

import tornado.web
    from tornado import gen
    from tornado import httpclient
     
    # 方式一:
    class AsyncHandler(tornado.web.RequestHandler):
        @gen.coroutine
        def get(self, *args, **kwargs):
            print('進入')
            http = httpclient.AsyncHTTPClient()
            data = yield http.fetch("http://www.google.com")
            print('完事',data)
            self.finish('6666')
     
    # 方式二:
    # class AsyncHandler(tornado.web.RequestHandler):
    #     @gen.coroutine
    #     def get(self):
    #         print('進入')
    #         http = httpclient.AsyncHTTPClient()
    #         yield http.fetch("http://www.google.com", self.done)
    #
    #     def done(self, response):
    #         print('完事')
    #         self.finish('666')
     
     
     
    application = tornado.web.Application([
        (r"/async", AsyncHandler),
    ])
     
    if __name__ == "__main__":
        application.listen(8888)
        tornado.ioloop.IOLoop.instance().start()
相關文章
相關標籤/搜索