20. How to use streaming with CherryPy

If you need to return a very big page to a browser, then you might want to use streaming, which means that CherryPy will start sending the page back to the browser before the page is completely built, and the page will be returned in chunks.

All you need to do to use streaming is to use the response.wfile variable, which contains the socket used to send the response back to the browser. You need to write all the data on the socket (including the response header).

You also need to tell CherryPy that you've already sent the response to the browser and therefore it doesn't have to do it. To do so, you need to set the response.sendResponse variable to 0.

The following code shows an example of how to use streaming:

import time
CherryClass Root:
view:
    def index(self):
        response.wfile.write("HTTP/1.1 200\r\n")
        response.wfile.write("Content-Type: text/plain\r\n\r\n")
        response.wfile.write("First line. Sleeping 2 seconds ...\n")
        time.sleep(2)
        response.wfile.write("Second line. Sleeping 2 seconds ...\n")
        time.sleep(2)
        response.wfile.write("Third and last line")
        response.sendResponse = 0
        return "" # The view still needs to return a string

See About this document... for information on suggesting changes.