memo

2014-07-15

Tornado ででかいデータ送信する

一定サイズごとに .write() した後に .flush() で待てばいいだけだった。

from tornado import gen, web


class ZeroHandler(web.RequestHandler):
    default_size = 1024
    buf_size = 4192

    @gen.coroutine
    def get(self):
        size = int(self.get_argument('size', self.default_size))

        self.set_header('Content-Type', 'application/octet-stream')
        self.set_header('Content-Length', str(size))

        remaining = size

        while remaining:
            if remaining > self.buf_size:
                self.write(b'\0' * self.buf_size)
                remaining -= self.buf_size
                yield self.flush()

            else:
                self.write(b'\0' * remaining)
                remaining = 0


if __name__ == '__main__':
    import tornado.ioloop

    application = web.Application([
        (r'/', ZeroHandler),
    ])

    application.listen(8080)
    tornado.ioloop.IOLoop.instance().start()