tornadod的异步代码

#!/usr/bin/env python
# -*- 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
# 这个并发库在python3.2版本以后自带, 在python2需要安装 sudo pip install futures
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 bbb" % res) self.finish() #@tornado.web.asynchonous装饰器时,Tornado永远不会自己关闭连接,需要显式的self.finish()关闭 @run_on_executor def sleep(self): time.sleep(6) return 6 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()

 详情请看:http://www.tuicool.com/articles/36ZzA3

      http://www.tuicool.com/articles/Ir2uai

posted @ 2016-12-09 15:08  我当道士那儿些年  阅读(301)  评论(0编辑  收藏  举报