首页 > 代码库 > tornadod的异步代码

tornadod的异步代码

#!/usr/bin/env python# -*- coding: utf-8 -*-import tornado.httpserverimport tornado.ioloopimport tornado.optionsimport tornado.webimport tornado.httpclientimport tornado.genfrom tornado.concurrent import run_on_executorfrom concurrent.futures import ThreadPoolExecutorimport timeclass 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 bbb" % res)        self.finish()    @run_on_executor    def sleep(self):        time.sleep(6)        return 6class 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()

 

tornadod的异步代码