Jas*_* Hu 0 python asynchronous tornado
以下是我的测试代码.我正在使用Python2.7,futures
安装使用:
pip install futures
Run Code Online (Sandbox Code Playgroud)
以下是我的演示代码:
import tornado.ioloop
import tornado.web
from tornado.gen import coroutine, Task
from tornado.concurrent import Future
import time
class MainHandler(tornado.web.RequestHandler):
@coroutine
def get(self):
print "in"
res = yield Task(self._work)
self.write(res)
def _work(self, callback):
time.sleep(10)
callback("hello world!")
if __name__ == "__main__":
application = tornado.web.Application([
(r"/", MainHandler),
])
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Run Code Online (Sandbox Code Playgroud)
这段代码应该同时进行,不应该吗?但是,它没有.
我用Firefox和IE测试过.我想我犯了一些错误.你指出我的错误会很高兴.
一次只有一个请求(http://localhost:8888/
:
import tornado.ioloop
import tornado.web
from tornado.gen import coroutine, Return, Task
from tornado.process import Subprocess
from tornado.concurrent import Future
from threading import Thread
import time
@coroutine
def async_sleep(timeout):
""" Sleep without blocking the IOLoop. """
yield Task(tornado.ioloop.IOLoop.instance().add_timeout, time.time() + timeout)
class MainHandler(tornado.web.RequestHandler):
@coroutine
def get(self):
print "in"
res = yield self._work()
self.write(res)
@coroutine
def _work(self):
yield async_sleep(5)
raise Return("hello world!")
if __name__ == "__main__":
application = tornado.web.Application([
(r"/", MainHandler),
])
application.listen(8888)
ioloop=tornado.ioloop.IOLoop.instance()
Thread(target=ioloop.start).start()
Run Code Online (Sandbox Code Playgroud)
由于您在评论中指出要通过龙卷风运行子流程,因此这里有一个示例说明如何执行此操作.我还修改了一个逻辑错误,你在创建一个Task
调用时_work
,它不会像你想象的那样工作:
import tornado.ioloop
import tornado.web
from tornado.gen import coroutine, Return
from tornado.process import Subprocess
from tornado.concurrent import Future
class MainHandler(tornado.web.RequestHandler):
@coroutine
def get(self):
print "in"
res = yield self._work()
self.write(res)
@coroutine
def _work(self):
p = Subprocess(['sleep', '10'])
f = Future()
p.set_exit_callback(f.set_result)
yield f
raise Return("hello world!")
if __name__ == "__main__":
application = tornado.web.Application([
(r"/", MainHandler),
])
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Run Code Online (Sandbox Code Playgroud)
如您所见,我制作_work
了一个协程,然后使用龙卷风的内置Subprocess
类来执行命令.我创建了一个Future
对象,并指示它在完成时Subprocess
调用Future.set_result(return_code_of_subprocess)
.然后我打电话yield
给Future
实例.这使代码等到子进程完成,而不会阻塞I/O循环.