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
Copy
--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
Copy
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 ( )
Copy
CABBY_SECRET = " change-me" CABBY_BROADCAST_KEY = " change-me-too" CABBY_BROADCAST_URL = " http://localhost:8080/_broadcast"
Copy
3. Pass a signed stream to the template
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 } " ) } )
Copy
from django . urls import path
from myapp import views
urlpatterns = [
path ( " rooms/<int:room_id>/" , views . room ) ,
]
Copy
Put the template in your app's templates folder. Add myapp to INSTALLED_APPS so Django
finds it.
< 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 >
Copy
4. Broadcast
from myapp . cabby import broadcast
broadcast ( f " room: { room_id } " , { " text" : " Hello" } )
Copy