Reputation: 548
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
But I can never see the last Hello
word...
What's wrong with my code ?
Upvotes: 1
Views: 552
Reputation: 14099
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.
Upvotes: 1
Reputation: 369454
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() # <------
Upvotes: 1