you*_*ang 4 asynchronous tornado
在文档中,如果方法也用@ gen.coroutine修饰,则不需要@ web.asynchronous.像这样
@web.asynchronous
@gen.coroutine
def get(self):
...
Run Code Online (Sandbox Code Playgroud)
但是,在文档中,他们还解释说如果你使用@ web.asynchronous,那么你应该调用self.finish().但是,在上面的情况下(一起使用两个装饰器)连接完成后调用"self.finish()"
我想知道那里发生了什么.
在下面的情况下,它与上述不同.
@web.asynchronous
def get(self):
self.test()
@gen.coroutine
def test(self):
httpClient = AsyncHttpClient()
val = yield httpClient.fetch("http://www.google.com")
print test
#self.finish()
Run Code Online (Sandbox Code Playgroud)
如果未调用"self.finish()",则表示连接未关闭.
有人可以解释一下吗?
秘密在这里:
if isinstance(result, Future):
# If @asynchronous is used with @gen.coroutine, (but
# not @gen.engine), we can automatically finish the
# request when the future resolves. Additionally,
# the Future will swallow any exceptions so we need
# to throw them back out to the stack context to finish
# the request.
def future_complete(f):
f.result()
if not self._finished:
self.finish()
IOLoop.current().add_future(result, future_complete)
Run Code Online (Sandbox Code Playgroud)
@asychronous检查返回未来的方法(即@gen.coroutine),如果是,则添加IOLoop回调以在将来完成时完成连接.