sse events sample
This commit is contained in:
44
openapi_first/templates/vet_app/sse.py
Normal file
44
openapi_first/templates/vet_app/sse.py
Normal 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)
|
||||
Reference in New Issue
Block a user