Skip to content
cabby

Django

Django uses the same standalone pattern as the Node.js guide: sign stream names on the server, subscribe in the browser and broadcast over HTTP.

1. Run Cabby

Install Cabby, then start it in standalone mode:

cabby --norpc --noauth --secret=change-me --broadcast_key=change-me-too --broadcast_adapter=http

--noauth lets visitors connect without logging in; the signed stream names decide what each one can read. --broadcast_adapter=http takes broadcasts over HTTP only, so you don't need Redis.

2. Add a small helper module

The helper uses requests for broadcasts:

pip install requests
# myapp/cabby.py
import base64
import hashlib
import hmac
import json

import requests
from django.conf import settings


def sign_stream(name: str) -> str:
    encoded = base64.b64encode(json.dumps(name).encode()).decode()
    digest = hmac.new(settings.CABBY_SECRET.encode(), encoded.encode(), hashlib.sha256).hexdigest()
    return f"{encoded}--{digest}"


def broadcast(stream: str, data: dict) -> None:
    response = requests.post(
        settings.CABBY_BROADCAST_URL,
        json={"stream": stream, "data": json.dumps(data)},
        headers={"Authorization": f"Bearer {settings.CABBY_BROADCAST_KEY}"},
        timeout=5,
    )
    response.raise_for_status()
# settings.py
CABBY_SECRET = "change-me"            # same as --secret
CABBY_BROADCAST_KEY = "change-me-too"  # same as --broadcast_key
CABBY_BROADCAST_URL = "http://localhost:8080/_broadcast"

3. Pass a signed stream to the template

# myapp/views.py
from django.shortcuts import render

from .cabby import sign_stream


def room(request, room_id):
    return render(request, "room.html", {"signed_stream": sign_stream(f"room:{room_id}")})
# urls.py
from django.urls import path

from myapp import views

urlpatterns = [
    path("rooms/<int:room_id>/", views.room),
]

Put the template in your app's templates folder. Add myapp to INSTALLED_APPS so Django finds it.

<!-- myapp/templates/room.html -->
<script type="module">
  import { createCable } from "https://cdn.jsdelivr.net/npm/@anycable/web@1/+esm"

  const cable = createCable("ws://localhost:8080/cable")
  const channel = cable.streamFromSigned("{{ signed_stream|escapejs }}")
  channel.on("message", (message) => console.log(message))
</script>

4. Broadcast

from myapp.cabby import broadcast

broadcast(f"room:{room_id}", {"text": "Hello"})