简体   繁体   English

添加@ tornado.web.asynchronous装饰器有什么好处?

[英]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 ? 我知道添加这个装饰器,我们应该手动调用self.finish() ,但这样做有什么好处?

Thanks ! 谢谢 !

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. 通常,当处理程序方法返回时,会为您调用finish() ,但如果您的处理程序依赖于异步计算的结果(如HTTP请求),那么在方法返回时它将不会完成。 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. 如果没有装饰器,在输入_on_download ,请求就已经完成了。

If your handler isn't doing anything async, then there's no benefit to adding the decorator. 如果你的处理程序没有做任何异步,那么添加装饰器没有任何好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM