π WebSockets ImplementationΒΆ
Duck makes WebSocket implementation simple and powerful π.
Forget the boilerplate β with Duck you can add real-time features in just a few lines of code π.
β‘ Quick ExampleΒΆ
In your urls.py, define a WebSocket view:
# urls.py
from duck.urls import path
from duck.contrib.websockets import WebSocketView, OpCode
class MyWebSocket(WebSocketView):
async def on_open(self):
print("WebSocket connection established")
async def on_receive(self, data: bytes, opcode: int):
if opcode == OpCode.TEXT:
message = "You sent " + data.decode("utf-8")
await self.send_text(message)
else:
# Handle binary frames here
pass
# Register your WebSocket route
urlpatterns = [
path("/ws/myws", MyWebSocket, name="mywebsocket"),
# other patterns here.
]
β Thatβs it! Your app is now ready to handle WebSocket connections.
βοΈ Customizing BehaviorΒΆ
Duckβs WebSocket views support configurable class variables:
β±
RECEIVE_TIMEOUTβ default:120seconds
(timeout before expecting a new frame).π¦
MAX_FRAME_SIZEβ default:1 * 1024 * 1024bytes
(maximum allowed size of a frame).
Simply override these in your WebSocketView subclass to tweak performance.
π¬ Practical ExamplesΒΆ
1οΈβ£ Simple Chat AppΒΆ
A minimal chat implementation that echoes messages back to all connected users.
from duck.contrib.websockets import WebSocketView, OpCode
connected_clients = set()
class ChatSocket(WebSocketView):
async def on_open(self):
connected_clients.add(self)
await self.send_text("π Welcome to the chat!")
async def on_receive(self, data: bytes, opcode: int):
if opcode == OpCode.TEXT:
message = data.decode("utf-8")
# Broadcast to all connected clients
for client in connected_clients:
if client != self:
await client.send_text(f"User: {message}")
async def on_close(self):
connected_clients.remove(self)
2οΈβ£ Live NotificationsΒΆ
Send server-initiated notifications to clients:
import asyncio
from duck.contrib.websockets import WebSocketView
from duck.utils.asyncio import create_task # Better than default asyncio.create_task
class NotificationSocket(WebSocketView):
async def on_open(self):
# Push notifications every 5 seconds
create_task(self.push_notifications())
async def push_notifications(self):
count = 0
while True:
await asyncio.sleep(5)
count += 1
await self.send_text(f"π Notification #{count}")
β¨ With Duckβs WebSocket support, you can build chat apps, live dashboards, multiplayer games, IoT streams, and more β all with async-native performance πβ‘
π Next: Learn how async fits into the bigger picture with β‘ ASGI or see how it plays with π₯οΈ WSGI.