vinaykp
vinaykp

Reputation: 549

Why I am not able to do simultaneous requests in Tornado?

Below tornado APP has 2 end points. One(/) is slow because it waits for an IO operation and other(/hello) is fast. My requirement is to make a request to both end points simultaneously.I observed it takes 2nd request only after it finishes the 1st one. Even though It is asynchronous why it is not able to handle both requests at same time ? How to make it to handle simultaneously?

Edit : I am using windows 7, Eclipse IDE

****************Module*****************
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.do_something()
        self.write("FINISHED")
        self.finish()

    def do_something(self):
        inp = input("enter to continue")
        print (inp)
class HelloHandler(tornado.web.RequestHandler):

    def get(self):
        print ("say hello")
        self.write("Hello bro")
        self.finish(
def make_app():
    return tornado.web.Application([
    (r"/", MainHandler),
    (r"/hello", HelloHandler)
])
if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

Upvotes: 0

Views: 1393

Answers (1)

deceze
deceze

Reputation: 521994

It is asynchronous only if you make it so. A Tornado server runs in a single thread. If that thread is blocked by a synchronous function call, nothing else can happen on that thread in the meantime. What @tornado.web.asynchronous enables is the use of generators:

@tornado.web.asynchronous
def get(self):
    yield from self.do_something()
    ^^^^^^^^^^

This yield/yield from (in current Python versions await) feature suspends the function and lets other code run on the same thread while the asynchronous call completes elsewhere (e.g. waiting for data from the database, waiting for a network request to return a response). I.e., if Python doesn't actively have to do something but is waiting for external processes to complete, it can yield processing power to other tasks. But since your function is very much running in the foreground and blocking the thread, nothing else will happen.

See http://www.tornadoweb.org/en/stable/guide/async.html and https://docs.python.org/3/library/asyncio.html.

Upvotes: 1

Related Questions