Make WebSocket lazy attributes definition possible (#2180)

This commit is contained in:
Andrea Giammarchi
2024-09-23 13:19:26 +02:00
committed by GitHub
parent a6b0964185
commit 5aaeebf32c

View File

@@ -5,6 +5,7 @@ from pyscript.util import as_bytearray
code = "code" code = "code"
protocols = "protocols" protocols = "protocols"
reason = "reason" reason = "reason"
methods = ["onclose", "onerror", "onmessage", "onopen"]
class EventMessage: class EventMessage:
@@ -37,7 +38,7 @@ class WebSocket(object):
socket = js.WebSocket.new(url) socket = js.WebSocket.new(url)
object.__setattr__(self, "_ws", socket) object.__setattr__(self, "_ws", socket)
for t in ["onclose", "onerror", "onmessage", "onopen"]: for t in methods:
if t in kw: if t in kw:
# Pyodide fails at setting socket[t] directly # Pyodide fails at setting socket[t] directly
setattr(socket, t, create_proxy(kw[t])) setattr(socket, t, create_proxy(kw[t]))
@@ -46,10 +47,11 @@ class WebSocket(object):
return getattr(self._ws, attr) return getattr(self._ws, attr)
def __setattr__(self, attr, value): def __setattr__(self, attr, value):
if attr == "onmessage": if attr in methods:
self._ws[attr] = lambda e: value(EventMessage(e)) m = lambda e: value(EventMessage(e))
setattr(self._ws, attr, create_proxy(m))
else: else:
self._ws[attr] = value setattr(self._ws, attr, value)
def close(self, **kw): def close(self, **kw):
if code in kw and reason in kw: if code in kw and reason in kw: