MCPcopy Create free account
hub / github.com/encode/starlette / send

Method send

starlette/websockets.py:65–104  ·  view source on GitHub ↗

Send ASGI websocket messages, ensuring valid state transitions.

(self, message: Message)

Source from the content-addressed store, hash-verified

63 raise WebSocketDisconnected('Cannot call "receive" once a disconnect message has been received.')
64
65 async def send(self, message: Message) -> None:
66 """
67 Send ASGI websocket messages, ensuring valid state transitions.
68 """
69 if self.application_state == WebSocketState.CONNECTING:
70 message_type = message["type"]
71 if message_type not in {"websocket.accept", "websocket.close", "websocket.http.response.start"}:
72 raise RuntimeError(
73 'Expected ASGI message "websocket.accept", "websocket.close" or "websocket.http.response.start", '
74 f"but got {message_type!r}"
75 )
76 if message_type == "websocket.close":
77 self.application_state = WebSocketState.DISCONNECTED
78 elif message_type == "websocket.http.response.start":
79 self.application_state = WebSocketState.RESPONSE
80 else:
81 self.application_state = WebSocketState.CONNECTED
82 await self._send(message)
83 elif self.application_state == WebSocketState.CONNECTED:
84 message_type = message["type"]
85 if message_type not in {"websocket.send", "websocket.close"}:
86 raise RuntimeError(
87 f'Expected ASGI message "websocket.send" or "websocket.close", but got {message_type!r}'
88 )
89 if message_type == "websocket.close":
90 self.application_state = WebSocketState.DISCONNECTED
91 try:
92 await self._send(message)
93 except OSError:
94 self.application_state = WebSocketState.DISCONNECTED
95 raise WebSocketDisconnect(code=1006)
96 elif self.application_state == WebSocketState.RESPONSE:
97 message_type = message["type"]
98 if message_type != "websocket.http.response.body":
99 raise RuntimeError(f'Expected ASGI message "websocket.http.response.body", but got {message_type!r}')
100 if not message.get("more_body", False):
101 self.application_state = WebSocketState.DISCONNECTED
102 await self._send(message)
103 else:
104 raise WebSocketDisconnected('Cannot call "send" once a close message has been sent.')
105
106 async def accept(
107 self,

Callers 9

acceptMethod · 0.95
send_textMethod · 0.95
send_bytesMethod · 0.95
send_jsonMethod · 0.95
closeMethod · 0.95
appFunction · 0.95
readerFunction · 0.45

Calls 4

WebSocketDisconnectClass · 0.85
_sendMethod · 0.80
getMethod · 0.45

Tested by 4

appFunction · 0.76
readerFunction · 0.36