Skip to content

Commit d3f1638

Browse files
committed
feat: changed examples for websockets
1 parent aa88710 commit d3f1638

File tree

1 file changed

+46
-14
lines changed

1 file changed

+46
-14
lines changed

content/index.yml

Lines changed: 46 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -88,29 +88,61 @@ hero:
8888
icon: i-lucide-unplug
8989
content: |
9090
::code-tree{defaultValue="main.py" class="lg:rounded-r-none lg:border-r-0 dark:[--ui-border-muted:var(--color-gray-800)]"}
91-
```python [main.py]
92-
import uvicorn
93-
from litestar import Litestar, websocket
94-
from litestar.connection import WebSocket
91+
```python [main_ws_listener.py]
92+
import dataclasses
93+
import datetime
94+
95+
from litestar import Litestar, websocket_listener
96+
97+
@dataclasses.dataclass()
98+
class Message:
99+
data: dict[str, str]
100+
timestamp: datetime.datetime
101+
102+
@websocket_listener("/echo")
103+
async def echo_handler(data: dict[str, str]) -> Message:
104+
"""
105+
Accept WebSocket connections on '/echo', and then for
106+
every incoming message:
107+
- Parse its content as JSON
108+
- Call 'echo_handler', passing the data to the 'data' parameter
109+
- Serialize the returned 'Message' dataclass to JSON
110+
- Send a WebSocket message back
111+
"""
112+
return Message(data=data, timestamp=datetime.now())
113+
114+
app = Litestar([handler])
115+
```
95116
96-
@websocket("/")
97-
async def echo_socket(socket: WebSocket) -> None:
98-
await socket.accept()
117+
```python [main_ws_stream.py]
118+
import asyncio
119+
import time
120+
from collections.abc import AsyncGenerator
121+
import dataclasses
122+
from litestar import Litestar, websocket_stream
123+
124+
@dataclass.dataclass()
125+
class Ping:
126+
timestamp: datetime.datetime
127+
128+
@websocket_stream("/ping")
129+
async def ping() -> AsyncGenerator[Ping, None]:
130+
"""
131+
Accept WebSocket connections on '/ping' an continue to
132+
send a 'Ping' message to the client
133+
"""
99134
while True:
100-
data = await socket.receive_text()
101-
await socket.send_text(f"Your message: {data}")
135+
yield Ping(timestamp=datetime.datetime.now())
136+
await asyncio.sleep(0.5)
102137
103-
app = Litestar(route_handlers=[echo_socket])
104-
105-
if __name__ == "__main__":
106-
uvicorn.run(app)
138+
app = Litestar([ping])
107139
```
108140
109141
```toml [pyproject.toml]
110142
[project]
111143
name = "litestar-websockets-echo"
112144
version = "0.1.0"
113-
description = "A Litestar websockets echo example"
145+
description = "A Litestar websockets stream and listener example"
114146
readme = "README.md"
115147
requires-python = ">=3.13"
116148
dependencies = [

0 commit comments

Comments
 (0)