Skip to content

Commit a04b264

Browse files
author
OSC Agent
committed
Add is_disconnected property to WebSocket
1 parent 9ee9519 commit a04b264

2 files changed

Lines changed: 22 additions & 0 deletions

File tree

starlette/websockets.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,13 @@ def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
3232
self.client_state = WebSocketState.CONNECTING
3333
self.application_state = WebSocketState.CONNECTING
3434

35+
@property
36+
def is_disconnected(self) -> bool:
37+
return (
38+
self.client_state == WebSocketState.DISCONNECTED
39+
or self.application_state == WebSocketState.DISCONNECTED
40+
)
41+
3542
async def receive(self) -> Message:
3643
"""
3744
Receive ASGI websocket messages, ensuring valid state transitions.

tests/test_websockets.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -651,3 +651,18 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
651651
with pytest.raises(RuntimeError):
652652
with client.websocket_connect("/") as websocket:
653653
websocket.send({"type": "websocket.connect"})
654+
655+
656+
def test_is_disconnected_property(test_client_factory: TestClientFactory) -> None:
657+
async def app(scope: Scope, receive: Receive, send: Send) -> None:
658+
websocket = WebSocket(scope, receive=receive, send=send)
659+
assert not websocket.is_disconnected
660+
await websocket.accept()
661+
assert not websocket.is_disconnected
662+
message = await websocket.receive()
663+
websocket.client_state = WebSocketState.DISCONNECTED
664+
assert websocket.is_disconnected
665+
666+
client = test_client_factory(app)
667+
with client.websocket_connect("/") as websocket:
668+
websocket.send_json({"close": True})

0 commit comments

Comments
 (0)