【发布时间】:2015-02-07 21:15:30
【问题描述】:
以下是我的测试代码。我使用的是 Python2.7,安装了futures:
pip install futures
以下是我的演示代码:
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()
这段代码应该同时运行,不是吗?然而,事实并非如此。
我用 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()
【问题讨论】:
-
你不能使用
time.sleep,因为那会阻塞tornado的I/O循环。您需要使用非阻塞方法来代替睡眠。有关示例,请参阅受骗问题。 -
@dano
sleep这是我认为的真正问题。在实践中,我将调用一个 bash 命令,这可能需要一段时间。有什么好的建议吗?
标签: python asynchronous tornado