tornado中,异步执行阻塞代码
2017-12-27 本文已影响0人
第八共同体
import time
import datetime
import tornado.ioloop
import tornado.web
import tornado.gen
import tornado.concurrent
from concurrent.futures import ThreadPoolExecutor
class MainHandler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(10)
@tornado.gen.coroutine
def get(self):
future = ThreadPoolExecutor().submit(self.blocksleep)
yield tornado.gen.with_timeout(datetime.timedelta(10), future,
quiet_exceptions=tornado.gen.TimeoutError)
self.write("Hello, world")
@tornado.concurrent.run_on_executor
def blocksleep(self):
time.sleep(20)
return
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()