tornado的异步效果

第一种方式:

import tornado.ioloop
import tornado.web
from tornado import gen
from tornado.concurrent import Future
import time

 

#########异步效果1,iploop
class MainHandler(tornado.web.RequestHandler):
@gen.coroutine##加一个装饰器
def get(self):
import time
###等待五秒种
future=Future()
self.write('hello,world ')
##五秒钟的超时时间,
tornado.ioloop.IOLoop.current().add_timeout(time.time()+5,self.doing)##等待五秒的时间
yield future
def doing(self,*args,**kwargs):
self.write('yibu ')
self.finish()


class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.write('index')

 

##下面是路由映射
appliaction=tornado.web.Application([
(r'/main',MainHandler),
(r'/index', IndexHandler),
])

 

 

 

 

 

 

 

第二种方式:

import tornado.ioloop
import tornado.web
from tornado import gen
from tornado.concurrent import Future
import time

 

######异步效果2,AsyncHTTPClient
class MainHandler(tornado.web.RequestHandler):
@gen.coroutine##加一个装饰器
def get(self):
import time
from tornado import httpclient
http=httpclient.AsyncHTTPClient()
yield http.fetch('http://www.geogle.com',self.doing )

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


class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.write('index')

 

##下面是路由映射
appliaction=tornado.web.Application([
(r'/main',MainHandler),
(r'/index', IndexHandler),
])

 

##settings配置
if __name__ == '__main__':
appliaction.listen(8000)
tornado.ioloop.IOLoop.instance().start()

 

 

 

第三种方式:

import tornado.ioloop
import tornado.web
from tornado import gen
from tornado.concurrent import Future
import time


#异步效果3,future
future=None
class MainHandler(tornado.web.RequestHandler):
@gen.coroutine##加一个装饰器
def get(self):
import time
global future
future=Future()
future.add_done_callback(self.doing)#####在这里设置返回值,future,当future里面的result值发生改变的时候就会触发这个的执行
yield future

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


class IndexHandler(tornado.web.RequestHandler):
def get(self):
global future
future.set_result(None)##设置返回值
self.write('index')

 

##下面是路由映射
appliaction=tornado.web.Application([
(r'/main',MainHandler),
(r'/index', IndexHandler),
])

##settings配置
if __name__ == '__main__':
appliaction.listen(8000)
tornado.ioloop.IOLoop.instance().start()

 

posted @ 2018-11-23 13:53  风不再来  阅读(211)  评论(0编辑  收藏  举报