Question
How do I stream content to the browser?
Answer
First, turn off debug mode in your ini file, or copy your development.ini file and uncomment the line:
1 | #set debug = false
|
When debug mode is on, streaming can't occur because the exception middleware needs to have the entire response finished first. Now that it's disabled, merely returning an iterator object or generator is sufficient to start streaming output.
Here's an example that sends a paragraph every 2 seconds:
1 2 3 4 5 6 7 8 9 10 11 | import time class StreamingController(object): def output(self): def output_pause(): num = 0 while 1: num += 1 yield num time.sleep(2) return output_pause() |
On loading /streaming/output, you should now see a number sent out every 2 seconds, continuing on forever.
Comments (2)
Jul 19, 2007
Dan Korostelev says:
Is this syntax only for Pylons 0.9.6? If yes, how to do that with old Response o...Is this syntax only for Pylons 0.9.6? If yes, how to do that with old Response object returning?
Jul 20, 2007
Ben Bangert says:
This will work in 0.9.5 as well.This will work in 0.9.5 as well.