| 89 | await self.on_disconnect(websocket, close_code) |
| 90 | |
| 91 | async def decode(self, websocket: WebSocket, message: Message) -> Any: |
| 92 | if self.encoding == "text": |
| 93 | if "text" not in message: |
| 94 | await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA) |
| 95 | raise RuntimeError("Expected text websocket messages, but got bytes") |
| 96 | return message["text"] |
| 97 | |
| 98 | elif self.encoding == "bytes": |
| 99 | if "bytes" not in message: |
| 100 | await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA) |
| 101 | raise RuntimeError("Expected bytes websocket messages, but got text") |
| 102 | return message["bytes"] |
| 103 | |
| 104 | elif self.encoding == "json": |
| 105 | if message.get("text") is not None: |
| 106 | text = message["text"] |
| 107 | else: |
| 108 | text = message["bytes"].decode("utf-8") |
| 109 | |
| 110 | try: |
| 111 | return json.loads(text) |
| 112 | except json.decoder.JSONDecodeError: |
| 113 | await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA) |
| 114 | raise RuntimeError("Malformed JSON data received.") |
| 115 | |
| 116 | assert self.encoding is None, f"Unsupported 'encoding' attribute {self.encoding}" |
| 117 | return message["text"] if message.get("text") else message["bytes"] |
| 118 | |
| 119 | async def on_connect(self, websocket: WebSocket) -> None: |
| 120 | """Override to handle an incoming websocket connection""" |