tornado异步

tornado异步

使用concurrent.futures,这个并发库在python3自带 ,在python2需要安装sudo pip install futures。安装tornado之后,可以直接用。这种方法是使用线程池或者进程池的方式实现异步的,它有ThreadPoolExecutorProcessPoolExecutor,要求Handler类要有一个名为executor的属性,指向一个Executor对象,代码如下:

import tornado.ioloop
import tornado.web
from tornado.concurrent import Future
from tornado.concurrent import run_on_executor

class BaseHandler(tornado.web.RequestHandler):
    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.set_header("Access-Control-Allow-Headers", "X-Requested-With, Ng-Path")
    def options(self):
        self.set_status(204)
        self.finish()

class MainHandler(BaseHandler):
    def get(self):
        self.write("Hello, world")

class Test1(BaseHandler):
    executor = futures.ThreadPoolExecutor(2)

    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self):
        ret = {}
        ret['success'] = True
        res = yield self.sleep()
        ret['data'] = res
        self.write(json.dumps(ret))

    @run_on_executor
    def sleep(self):
        time.sleep(5)
        return 5

def make_app():
    application = tornado.web.Application([
        (r"/", MainHandler),
        (r"/risk/test1", Test1),
    ])
    return application


if __name__ == "__main__":
    print 'tornado running...'
    app = make_app()
    app.listen(9090)
    tornado.ioloop.IOLoop.current().start()

你可能感兴趣的:(tornado异步)