I'm trying to stream Server-Sent Events from my Pyramid application, but I can't figure out how to stream the response body from my view. Here's the test view I'm using (it totally doesn't implement SSE, it's just to work out the streaming portion):
@view_config(route_name='iter_test')
def iter_test(request):
import time
def test_iter():
i = 0
while True:
i += 1
if i == 5:
raise StopIteration
yield str(time.time())
print time.time()
time.sleep(1)
return test_iter()
This produces ValueError: Could not convert return value of the view callable function pdiff.views.iter_test into a response object. The value returned was <generator object test_iter at 0x3dc19b0>.
I've tried return Response(app_iter=test_iter())
instead, which at least doesn't error out, but it doesn't stream the response - it waits until the generator has completed before returning the response to my browser.
I recognize that could simply return a single event per request and allow the clients to reconnect after each event, but I'd prefer to preserve the realtime nature of Server-Sent Events by streaming multiple events from a single request, without the reconnection delay. How can I do this with Pyramid?