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
"
elif not x % 5:
yield "Buzz
"
elif not x % 3:
yield "Fizz
"
else:
yield "%s
" % x
How can I make this handler work asynchronously?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…