简体   繁体   English

我的python龙卷风代码不起作用...为什么

[英]My python tornado code doesn't work… why

I have two Handler class to compare the @tornado.web.asynchronous decorator 我有两个Handler类来比较@ tornado.web.asynchronous装饰器

class Test1Handler(tornado.web.RequestHandler):  
    def get(self):  
        for i in range(1, 100000):  
            print "kill time"  
        self.write("hello")  

class Test2Handler(tornado.web.RequestHandler):  
    @tornado.web.asynchronous
    def get(self):  
        http = tornado.httpclient.AsyncHTTPClient()  
        http.fetch("http://localhost:8005/test1", callback=self._test_callback)  
        self.write("Hello to the Tornado world! ")  

    def _test_callback(self, response): 
        print response.body
        self.write(response.body)  

The following is the configuration code 以下是配置代码

app = tornado.web.Application([
    (r'/test1', Test1Handler),
    (r'/test2', Test2Handler)], debug=True)
app.listen(8005)
tornado.ioloop.IOLoop.instance().start()

OK, when I run http://localhost:8005/test1 I can see the hello after several seconds... 好的,当我run http://localhost:8005/test1 ,几秒钟后我可以看到你好...

However when I run http://localhost:8005/test2 , the page is just loading and loading... I should see Hello to the Tornado world! Hello 但是,当我run http://localhost:8005/test2 ,页面正在加载和加载...我应该看到Hello to the Tornado world! Hello Hello to the Tornado world! Hello But I can never see the last Hello word... Hello to the Tornado world! Hello但我再也看不到Hello好话

What's wrong with my code ? 我的代码有什么问题?

You need to explicitly call finish method to finish http request when you're using tornado.web.asynchronous decorator. 使用tornado.web.asynchronous装饰器时,需要显式调用finish方法来完成http请求。

def _test_callback(self, response): 
    self.write(response.body)  
    self.finish()  # <------

You seem to be missing a self.finish() in the handler decorated as asynchronous . 您似乎在装饰为异步的处理程序中缺少self.finish()

If this decorator is given, the response is not finished when the method returns. 如果指定了此装饰器,则方法返回时响应不会结束。 It is up to the request handler to call self.finish() to finish the HTTP request. 由请求处理程序调用self.finish()完成HTTP请求。

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

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