Domanda

I just thought about the non-blocking infrastructure of tornado and event-driven programming. Actually I'm writing a simple webapp which is accessing a HTTP-API of an external webservice. I understand why I should call this API non-blocking. But are there any disadvantages if I do just the first call non-blocking, so that the IOLoop can loop further?

For Example:

@tornado.web.asynchronous
def get(self):
    nonblocking_call1(self._callback)

def _callback(self, response):
    self.write(str(response))
    self.write(str(blocking_call2()))
    self.write(str(blocking_call3()))
    self.finish()

vs.

@tornado.web.asynchronous
def get(self):
    nonblocking_call1(self._nonblocking_callback1)

def _callback1(self, response):
    self.write(str(response))
    nonblocking_call2(self._nonblocking_callback2)

def _callback2(self, response):
    self.write(str(response))
    nonblocking_call3(self._nonblocking_callback3)

def _callback3(self, response):
    self.write(str(response))
    self.finish()
È stato utile?

Soluzione

If you use blocking code inside tornado, the same tornado process can not process any other requests while any blocking code is waiting. Your app will not support more than one simultaneous user, and even if the blocking call only takes something like 100ms, it will still be a HUGE performance killer.

If writing this way is exhausting for you (it is for me), you can use tornado's gen module:

class GenAsyncHandler(RequestHandler):
    @asynchronous
    @gen.engine
    def get(self):
        http_client = AsyncHTTPClient()
        response = yield gen.Task(http_client.fetch, "http://example.com")
        do_something_with_response(response)
        self.render("template.html")
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top