Search code examples
pythonstreamingcherrypyyield

How to stream data with Cherrypy


The following code should send 4 lines of text to the browser, 1 line per second.

Instead the browser (I tried with Chrome and IE) waits 4 seconds and shows the 4 lines at the same time. The snippet shows two lines setting the header. I tried with both, but neither works.

What am I doing wrong?

import cherrypy
import time

class Root:

    @cherrypy.expose
    def index(self):
        cherrypy.response.headers['Content-Type'] = 'text/event-stream'  # see http://stackoverflow.com/questions/20837460/firefox-doesnt-restore-server-sent-events-connection
        cherrypy.response.headers['Content-Type'] = 'text/plain'         # see http://cherrypy.readthedocs.org/en/latest/advanced.html#how-streaming-output-works-with-cherrypy

        def streamer():
            for i in range(3):
                time.sleep(1)
                yield '{} {}\n'.format(time.asctime(), i+1)
                print(i)

            time.sleep(1)
            yield '{} Done'.format(time.asctime())

        return streamer()

    index._cp_config = {'response.stream': True}

cherrypy.quickstart(Root())

Solution

  • You are not doing anything wrong. It depends on the browser. For this sort of debugging use something like curl -v or curl --trace-ascii -. It shows each line arriving with a timeout as you expect. Should also work with firefox.