anna-money / asyncpg-listen

A thing to simplify listening for PG notifications with asyncpg
MIT License
36 stars 2 forks source link

How do I pass additional args to the callback func #175

Open mikcatta opened 1 year ago

mikcatta commented 1 year ago

I am trying to implement this in a FastAPI/Websockets app, so that when a table update has been made, the changes (or a simple message) is pushed back to the listening client. Each client could potentially be listening to different channels, in this example they are all listening to "customer2" .

What I need is to pass the websocket argument to the notification handler, so that instead of just printing it, it sends back the payload to whichever client was listening. This is where I am a bit stuck, as my knowledge of asyncio is limited. Any help most appreciated.

` @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept()

try:
    listener = asyncpg_listen.NotificationListener(asyncpg_listen.connect_func(dsn))
    listener_task = asyncio.create_task(
      listener.run(
        {"customer2": handle_notifications},
        policy=asyncpg_listen.ListenPolicy.LAST,
        notification_timeout=50
        )
    )
    # add it to the list so they can be closed if the server is shutdown
    all_listener_tasks.append(listener_task)

except WebSocketDisconnect:
    logger.info('Client has disconnected') # maybe more needs to be done to clean up ....
    return

async def handle_notifications(notification: asyncpg_listen.NotificationOrTimeout) -> None: print(f"{notification} has been received, sent to websocket ?") `

bitnom commented 1 year ago

I'm about to need to do this in Blacksheep. Will report back what happens.

baklim commented 4 months ago

You can use functools.partial.