However, remove_connection() is not async so should not be awaited. Furthermore, the type of msg in the example is a dict and since the broadcast() method only accepts the Message type, this can't actually be used. The topic param isn't being passed to new_connection() either.
Similar story to the example after:
@app.websocket('/ws/{conn_id}')
async def websocket_endpoint(
ws: WebSocket,
conn_id: str,
*,
topic: Optional[Any] = None,
) -> None:
connection: Connection = await manager.new_connection(ws, conn_id)
# This is the preferred way of handling WebSocketDisconnect
async for msg in connection.iter_json():
await manager.receive(connection, msg)
await manager.remove_connection(connection)
remove_connection() is not async.
iter_json() is also returning dicts which don't fit with the receive() method.
topic param is unused.
Pitch
The first example could become something like this:
There's a lot of potential solutions though. You could
Add a receive_message() method to abstract the conversion to Message object
Change broadcast() to detect the type of the message arg
Add a broadcast_json() method instead
For the second example, it could be something like this:
@app.websocket('/ws/{conn_id}')
async def websocket_endpoint(
ws: WebSocket,
conn_id: str,
*,
topic: Optional[Any] = None,
) -> None:
connection: Connection = await manager.new_connection(ws, conn_id, topic)
# This is the preferred way of handling WebSocketDisconnect
async for msg in connection:
await manager.receive(connection, msg)
manager.remove_connection(connection)
Just a side-note but it could be cool to see some sort of context manager or putting into an iter so that it removes the connection on WebSocketDisconnect automatically.
Feature or enhancement
Make the
README.md
examples consistent with how the library actually works.Issue
One of the examples of how to receive data in the
README.md
is as follows:However,
remove_connection()
is not async so should not be awaited. Furthermore, the type ofmsg
in the example is adict
and since thebroadcast()
method only accepts theMessage
type, this can't actually be used. Thetopic
param isn't being passed tonew_connection()
either.Similar story to the example after:
remove_connection()
is not async.iter_json()
is also returningdict
s which don't fit with thereceive()
method.topic
param is unused.Pitch
The first example could become something like this:
There's a lot of potential solutions though. You could
receive_message()
method to abstract the conversion to Message objectbroadcast()
to detect the type of themessage
argbroadcast_json()
method insteadFor the second example, it could be something like this:
Just a side-note but it could be cool to see some sort of context manager or putting into an iter so that it removes the connection on
WebSocketDisconnect
automatically.