Django Channels brings WebSocket support to Django, and Pytigon wraps it with a clean, convention-based interface. Define consumers, connect to rooms, and push real-time updates — all without leaving the Pytigon ecosystem.
Create a file consumers.py in your application directory. Pytigon auto-discovers it:
# [app_name]/consumers.py
from pytigon_lib.schdjangoext.channels_utils import PtigJsonWebsocketConsumer
class MyConsumer(PtigJsonWebsocketConsumer):
def connect(self):
# Called when a WebSocket connection is established
self.room_group_name = "my_room"
self.accept()
def receive_json(self, content):
# Called when JSON data arrives from the client
action = content.get("action")
if action == "ping":
self.send_json({"action": "pong"})
def table_update(self, event):
# Called when a table update event is received
self.send_json(event["data"])
Use Django Channels' layer system to broadcast to groups:
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
def notify_table_change(table_name, record_id):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
f"table_{table_name}",
{
"type": "table_update",
"data": {"table": table_name, "id": record_id}
}
)
The Pytigon JavaScript library automatically handles WebSocket connections:
// Connection is established automatically
// Listen for server-sent events
ptig.socket.on('table_update', function(data) {
if (data.table === 'MyTable') {
ptig.table.refresh();
}
});
// Send data to server
ptig.socket.send({
action: 'subscribe',
table: 'MyTable',
filter: 'active'
});
In production, configure Redis as the channel layer backend:
# settings_app.py
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("127.0.0.1", 6379)],
},
},
}
For development, the in-memory layer works without any external dependencies.