# coding=utf-8
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
import tornado.gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
import time
class SleepHandler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(2)
@tornado.web.asynchronous
@tornado.gen.coroutine
def get(self):
"""
若是要实现异步并且该请求需要等待执行结果则加入yield
否则可以将yield去掉,程序会继续往下执行
"""
res = yield self.sleep()
self.write("when i sleep %s s" % res)
self.finish()
@run_on_executor
def sleep(self):
time.sleep(5)
return 5
class NormalHandler(tornado.web.RequestHandler):
def get(self):
self.write("normal handler")
if __name__ == "__main__":
app = tornado.web.Application(handlers=[
(r"/sleep", SleepHandler), (r"/normal", NormalHandler)])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
网友评论