Handler outside of websocket definition

How can I send data in a certain function outside the handler where the websocket is defined. (I can’t lie, I’m struggling to find out how to add codeblocks onto this).

You could try something like this:

async def producer(send):
    print("start producer")
    while True:
        try:
            await send("hello")
        except (
            websockets.exceptions.ConnectionClosedError,
            websockets.exceptions.ConnectionClosedOK,
        ):
            print("closing producer")
            break
        await asyncio.sleep(1)


async def consumer(recv):
    print("start consumer")
    while True:
        message = await recv()
        if not message:
            break
        print(message)
    print("closing consumer")


@app.websocket("/feed")
async def feed(request, ws):
    print("start socket")
    request.app.add_task(producer(ws.send))
    await consumer(ws.recv)
    print("closing socket")
    await ws.close()

There’s also a more involved setup involving a Redis pubsub if you are interested: https://gist.github.com/ahopkins/9816b39aedb2d409ef8d1b85f62e8bec

EDIT newer version: https://gist.github.com/ahopkins/5b6d380560d8e9d49e25281ff964ed81

1 Like