16

I have a python generator function which yields chunks of text. I would like to write a get method for a tornado.web.RequestHandler subclass that will iterate over the generator, writing the chunks out to the response as it goes.

Since this is Tornado, and since the generator may take over a second to process, I thought it would be nice to make the handler asynchronous, using this generator as a co-routine and passing off control to the IOLoop after every chunk. However, I can't make heads or tails of how to do this.

Here's my example (blocking) code:

class TextHandler(web.RequestHandler):
    @web.asynchronous
    def get(self, n):
        generator = self.generate_text(100000)
        # Clearly, this will block. How to make it asynchronous?
        for text in generator:
            self.write(text)

    def generate_text(n):
        for x in xrange(n):
            if not x % 15:
                yield "FizzBuzz\n"
            elif not x % 5:
                yield "Buzz\n"
            elif not x % 3:
                yield "Fizz\n"
            else:
                yield "%s\n" % x

How can I make this handler work asynchronously?

2
  • It's not really clear what are you going to achieve. Do you want to leave get() before all the generator values were iterated and than get back when new values are ready? If so, than you cannot do that. In this particular function your code is single threaded and if you quit then you loose context. On the other hand, method marked as asynchronous which usually implies handler is called form a thread pool so, it should be OK to block there.
    – real4x
    Jan 11, 2012 at 5:43
  • As long as the generator exists, it has all the context I need. That's the beauty of generators: co-routines in a single thread. Of course, you have to handle the scheduling yourself, which is perhaps the real problem here.
    – David Eyk
    Jan 11, 2012 at 16:12

2 Answers 2

16

Here's a basic version of what you are describing. To avoid blocking you can pass your generator to the IOLoop via a callback function. The trick here is since you are not using a process that does actual IO and so has no os level process/file handler to add to the IOLoop via add_handler, you can instead use a simple add_callback call and call it repeatedly from within the callback function to keep the function in the IOLoop callback queue until the generator has finished.

import tornado.httpserver
import tornado.ioloop
import tornado.web

class TextHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.generator = self.generate_text(1000)
        tornado.ioloop.IOLoop.instance().add_callback(self.loop)

    def loop(self):
        try:
            text = self.generator.next()
            self.write(text)
            tornado.ioloop.IOLoop.instance().add_callback(self.loop)
        except StopIteration:
            self.finish()

    def generate_text(self, n):
        for x in xrange(n):
            if not x % 15:
                yield "FizzBuzz\n"
            elif not x % 5:
                yield "Buzz\n"
            elif not x % 3:
                yield "Fizz\n"
            else:
                yield "%s\n" % x

application = tornado.web.Application([
    (r"/text/", TextHandler),
])

http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
2
  • Why yes, that looks like exactly what I want. I hadn't thought of having the loop schedule itself as a callback.
    – David Eyk
    Jan 11, 2012 at 16:13
  • 1
    @philofinfinitejest Minor remark, it is better to use IOLoop.current() instead of IOLoop.instance(). In my case that was crusial. It is also recommended by the docs
    – prokher
    May 31, 2015 at 21:29
14

It is also possible to use the new tornado's gen interface to async processes:

import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.gen

class TextHandler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self):

        def cb(it, callback):
            try:
                value = it.next()
            except StopIteration:
                value = None
            callback(value)

        it = self.generate_text(1000)
        while True:
            response = yield tornado.gen.Task(cb, it)
            if response:
                self.write(response)
            else:
                break
        self.finish()

    def generate_text(self, n):
        for x in xrange(n):
            if not x % 15:
                yield "FizzBuzz\n"
            elif not x % 5:
                yield "Buzz\n"
            elif not x % 3:
                yield "Fizz\n"
            else:
                yield "%s\n" % x

application = tornado.web.Application([
    (r"/text/", TextHandler),
])

http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
3
  • I think I see what's going on there, but the flow of control is more mysterious (w/o having a deep understanding of what gen.Task does behind the scenes). @cptphil's use of scheduled callbacks is much more straightforward.
    – David Eyk
    Jan 11, 2012 at 18:24
  • Also, it might be better to use if response is not None instead of if response, in case we're using a generator that yields empty strings. The example won't, but my actual use case will. :)
    – David Eyk
    Jan 11, 2012 at 18:25
  • Any further documentation on Task? I'm struggling to understand the bigger picture from reading the source.
    – Cuadue
    May 17, 2013 at 2:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.