美文网首页
[code]Tornado实现异步代码

[code]Tornado实现异步代码

作者: PyKailyn | 来源:发表于2016-08-11 16:39 被阅读0次
    # 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()
    

    相关文章

      网友评论

          本文标题:[code]Tornado实现异步代码

          本文链接:https://www.haomeiwen.com/subject/fclssttx.html