sse events sample

This commit is contained in:
2026-06-18 01:21:40 +05:30
parent 69b795f9ca
commit 083fb6923d
4 changed files with 95 additions and 0 deletions

View File

@@ -0,0 +1,44 @@
"""
SSE broadcast for the animal-sounds worker.
Not part of the openapi_first library API surface.
"""
import asyncio
import random
import json
_sounds = ["woof", "meow", "coo"]
_subscribers: list[asyncio.Queue] = []
_worker_task: asyncio.Task | None = None
async def _sound_worker():
while True:
sound = random.choice(_sounds)
data = json.dumps({"sound": sound})
for q in _subscribers:
await q.put(data)
await asyncio.sleep(random.uniform(1, 5))
def start_worker():
global _worker_task
_worker_task = asyncio.create_task(_sound_worker())
def stop_worker():
if _worker_task is not None:
_worker_task.cancel()
async def subscribe() -> asyncio.Queue:
q: asyncio.Queue = asyncio.Queue()
_subscribers.append(q)
return q
def unsubscribe(q: asyncio.Queue):
if q in _subscribers:
_subscribers.remove(q)