0

My python version is 3.4, my tornado version is 4.3.My code is like this:

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


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        body = 'foobar'*10
        self.set_header('Transfer-Encoding', 'chunked')
        self.write(body)
        self.flush()
        self.finish()


app = tornado.web.Application([
        (r'/chunked', MainHandler),
])

if __name__ == "__main__":
    app.listen(8080)
    tornado.ioloop.IOLoop.current().start()

This simply can not work, client just wait for the chunk ends.How to generate a chunked response properly when using tornado server?

user1021531
  • 487
  • 1
  • 7
  • 16

1 Answers1

6

A single call to write will result in a single chunk in the response. To get multiple chunks you must call write several times, flush each time, and yield in between (if you're not yielding anything then there is no value in using chunks for the response).

@tornado.gen.coroutine
def get(self):
    for i in range(10):
        self.write('foobar')
        yield self.flush()
Ben Darnell
  • 21,844
  • 3
  • 29
  • 50
  • 1
    Also, do not set the Transfer-Encoding header by hand (unless you also generate all the chunked-encoding framing). That's for the server framework to control. – Ben Darnell Dec 02 '16 at 16:02