简体   繁体   中英

My python tornado code doesn't work… why

I have two Handler class to compare the @tornado.web.asynchronous decorator

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...

However when I run http://localhost:8005/test2 , the page is just loading and loading... I should see Hello to the Tornado world! Hello Hello to the Tornado world! Hello But I can never see the last Hello word...

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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