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: Sanic based websocket pubsub feed · GitHub