From c573019e7fe6f494bfe2681b8d876080a5d0c3d8 Mon Sep 17 00:00:00 2001 From: Adam Hopkins Date: Sun, 25 Dec 2022 13:52:07 +0200 Subject: [PATCH] ASGI websocket recv text or bytes (#2640) --- sanic/server/websockets/connection.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/sanic/server/websockets/connection.py b/sanic/server/websockets/connection.py index c53a65a5..87881b84 100644 --- a/sanic/server/websockets/connection.py +++ b/sanic/server/websockets/connection.py @@ -9,8 +9,10 @@ from typing import ( Union, ) +from sanic.exceptions import InvalidUsage -ASIMessage = MutableMapping[str, Any] + +ASGIMessage = MutableMapping[str, Any] class WebSocketConnection: @@ -25,8 +27,8 @@ class WebSocketConnection: def __init__( self, - send: Callable[[ASIMessage], Awaitable[None]], - receive: Callable[[], Awaitable[ASIMessage]], + send: Callable[[ASGIMessage], Awaitable[None]], + receive: Callable[[], Awaitable[ASGIMessage]], subprotocols: Optional[List[str]] = None, ) -> None: self._send = send @@ -47,7 +49,13 @@ class WebSocketConnection: message = await self._receive() if message["type"] == "websocket.receive": - return message["text"] + try: + return message["text"] + except KeyError: + try: + return message["bytes"].decode() + except KeyError: + raise InvalidUsage("Bad ASGI message received") elif message["type"] == "websocket.disconnect": pass