tornado what is the difference between @web.asynchronous @gen.coroutine VS @gen.corutine

亡梦爱人 提交于 2019-12-09 06:42:04

问题


In the document, @web.asynchronous is unnecessary if the method is also decorated with @gen.coroutine. like this

@web.asynchronous
@gen.coroutine
def get(self):
    ...

but, In document, They also explain that If you use @web.asynchronous, then you should call self.finish(). However, In above case(using two decorator together) the connection is finished with out calling "self.finish()"

I'm wondering what happened in there.

and In below case, It works different with above.

@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()

If "self.finish()" is not called the connection is not closed.

Is there anybody can explain this?


回答1:


The secret is here:

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)

@asychronous checks for the method returning a future (i.e. @gen.coroutine) and if so, adds an IOLoop callback to finish the connection when the future completes.



来源:https://stackoverflow.com/questions/22967996/tornado-what-is-the-difference-between-web-asynchronous-gen-coroutine-vs-gen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!