python tornado异步处理记录

单进程单线程。

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        time.sleep(10)
        return "ok"

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(58000)
    tornado.ioloop.IOLoop.instance().start()

异步写法

#!/bin/env python
# -*- coding:utf-8 -*-
# Date:        2017-01-02
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
## END INIT INFO
import tornado.ioloop
import tornado.web
import tornado.gen
from tornado.concurrent import run_on_executor
# 这个并发库在python3自带;在python2需要安装pip install futures
from concurrent.futures import ThreadPoolExecutor
import time

class MainHandler(tornado.web.RequestHandler):
    #executor 是局部变量  不是全局的
    executor = ThreadPoolExecutor(5)
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self):
        res = yield self.sleep()
        self.write("wait. %s" % res)
        # 必须要结束
        self.finish()

    @run_on_executor
    def sleep(self):
        time.sleep(10)
        return "ok"

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(58000)
    tornado.ioloop.IOLoop.instance().start()

来源:http://www.dongwm.com/archives/shi-yong-tornadorang-ni-de-qing-qiu-yi-bu-fei-zu-sai/

发表评论

电子邮件地址不会被公开。 必填项已用*标注