Skip to content

Commit

Permalink
ASGI websocket recv text or bytes (#2640)
Browse files Browse the repository at this point in the history
  • Loading branch information
ahopkins committed Dec 25, 2022
1 parent 029f564 commit c573019
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions sanic/server/websockets/connection.py
Expand Up @@ -9,8 +9,10 @@
Union,
)

from sanic.exceptions import InvalidUsage

ASIMessage = MutableMapping[str, Any]

ASGIMessage = MutableMapping[str, Any]


class WebSocketConnection:
Expand All @@ -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
Expand All @@ -47,7 +49,13 @@ async def recv(self, *args, **kwargs) -> Optional[str]:
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

Expand Down

0 comments on commit c573019

Please sign in to comment.