Tornado之異步非阻塞

 同步模式:同步模式下,只有處理完前一個任務下一個纔會執行web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        time.sleep(10)
        self.write("Hello, world")

application = tornado.web.Application([
    (r"/index", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()

 

tornado如何使用異步非阻塞:app

  -Future對象異步

  -IO事件循環async

  -生成器ide

異步模式tornado

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

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()
application = tornado.web.Application([ (r"/index",AsyncHandler),
])
 
 
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
 

 

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

異步非阻塞體如今當在Tornaod等待用戶向future對象中放置數據時,還能夠處理其餘請求。在等待用戶向future對象中放置數據或信號時,此鏈接是不斷開的。fetch

 

簡單實現的異步非阻塞google

# Author:song
import tornado.web
import tornado.ioloop
from tornado import gen
from tornado.concurrent import Future
import time

class MainHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self):
        future = Future()
        tornado.ioloop.IOLoop.current().add_timeout(time.time() + 5, self.done)#模擬出現阻塞
        yield future

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


class LoginHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('登陸')
    def post(self, *args, **kwargs):
        print(self.get_argument('user'))
        self.redirect('https://home.cnblogs.com/u/master-song/')

application = tornado.web.Application([
    (r"/main", MainHandler),
    (r"/login", LoginHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
tornado_async

Tornado提供了httpclient類庫用於發送Http請求,其配合Tornado的異步非阻塞使用

class MainHandler(tornado.web.RequestHandler):

    @gen.coroutine
    def get(self):
        http = httpclient.AsyncHTTPClient()
        yield http.fetch("http://www.google.com", self.done)

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

 

future=Future()

1.掛起當前請求,線程能夠處理其餘請求

2.future設置值,當前掛起請求返回

相關文章
相關標籤/搜索