def eventstream(): sse = Sse() pubsub = redis.pubsub() while True: for event in event_types: pubsub.subscribe(event) with Timeout(TIMEOUT) as timeout: try: for message in pubsub.listen(): if message['type'] != "message": continue try: data = json.loads(message['data']) except ValueError: # broken json continue if 'site_id' not in data or data['site_id'] != SITE_ID: continue sse.add_message(message['channel'], str(message['data'])) for event in sse: yield str(event) sse.flush() timeout.cancel() timeout.start() # heartbeat, to detect if a user is disconnected except Timeout as t: if t is not timeout: # not our timeout raise yield ":\n\n" # heartbeat message finally: pubsub.close()
def test_flush(self): sse = Sse() sse.add_message("foo", "bar") sse.flush() self.assertEqual(len(sse._buffer), 0)