Using a simple python generator as a co-routine in a Tornado async handler?

后端 未结 2 1941
梦谈多话
梦谈多话 2020-12-08 03:19

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 w

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 04:02

    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()
    

提交回复
热议问题