Search code examples
pythontornado

What is the benefit of adding a @tornado.web.asynchronous decorator?


class IndexHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(request):
        request.render("../resouce/index.html")

I always read some tornado code as above, confusing that what's the purpose of adding this decorator ? I know that adding this decorator, we should call self.finish()manually, but any benefits of doing that ?

Thanks !


Solution

  • Normally, finish() is called for you when the handler method returns, but if your handler depends on the result of an asynchronous computation (like an HTTP request), then it won't have finished by the time the method returns. Instead it should finish in some callback.

    The example from the documentation is instructive:

    class MyRequestHandler(web.RequestHandler):
        @web.asynchronous
        def get(self):
           http = httpclient.AsyncHTTPClient()
           http.fetch("http://friendfeed.com/", self._on_download)
    
        def _on_download(self, response):
           self.write("Downloaded!")
           self.finish()
    

    Without the decorator, by the time _on_download is entered the request would have finished already.

    If your handler isn't doing anything async, then there's no benefit to adding the decorator.