MCPcopy Index your code
hub / github.com/pyscript/pyscript / __init__

Method __init__

core/src/stdlib/pyscript/websocket.py:178–222  ·  view source on GitHub ↗

Create a new WebSocket connection from the given `url` (`ws://` or `wss://`). Optionally specify `protocols` (a string or a list of protocol strings) and event handlers (`onopen`, `onmessage`, etc.) as keyword arguments. These arguments and naming convention

(self, url, protocols=None, **handlers)

Source from the content-addressed store, hash-verified

176 CLOSED = 3
177
178 def __init__(self, url, protocols=None, **handlers):
179 """
180 Create a new WebSocket connection from the given `url` (`ws://` or
181 `wss://`). Optionally specify `protocols` (a string or a list of
182 protocol strings) and event handlers (`onopen`, `onmessage`, etc.) as
183 keyword arguments.
184
185 These arguments and naming conventions mirror those of the
186 [underlying JavaScript WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
187 for familiarity.
188
189 If you need access to the underlying JavaScript WebSocket instance,
190 you can get it via the `_js_websocket` attribute.
191
192 ```python
193 # Basic connection.
194 ws = WebSocket(url="ws://localhost:8080/")
195
196 # With protocol.
197 ws = WebSocket(
198 url="wss://example.com/socket",
199 protocols="chat"
200 )
201
202 # With handlers.
203 ws = WebSocket(
204 url="ws://localhost:8080/",
205 onopen=lambda e: print("Connected"),
206 onmessage=lambda e: print(e.data)
207 )
208 ```
209 """
210 # Create underlying JavaScript WebSocket.
211 if protocols:
212 js_websocket = js.WebSocket.new(url, protocols)
213 else:
214 js_websocket = js.WebSocket.new(url)
215 # Set binary type to arraybuffer for easier Python handling.
216 js_websocket.binaryType = "arraybuffer"
217 # Store the underlying WebSocket.
218 # Use object.__setattr__ to bypass our custom __setattr__.
219 object.__setattr__(self, "_js_websocket", js_websocket)
220 # Attach any event handlers passed as keyword arguments.
221 for handler_name, handler in handlers.items():
222 setattr(self, handler_name, handler)
223
224 def __getattr__(self, attr):
225 """

Callers

nothing calls this directly

Calls 1

__setattr__Method · 0.45

Tested by

no test coverage detected