Using Relay with Django
Broadcast WebSocket events from your Django app using Relay's Pusher-compatible HTTP API.
Skip the server setup. Relay Cloud gives you managed WebSockets with a free tier. Connect in 60 seconds.
Try free →
Prerequisites
- Python 3.8+
- A running Relay server
- Your App Key, Secret, and App ID
1
Install the Pusher SDK
pip install pusher
2
Configure settings.py
RELAY_APP_ID = os.environ.get('RELAY_APP_ID')
RELAY_APP_KEY = os.environ.get('RELAY_APP_KEY')
RELAY_APP_SECRET = os.environ.get('RELAY_APP_SECRET')
RELAY_HOST = os.environ.get('RELAY_HOST', 'ws.relaycloud.dev')
RELAY_PORT = int(os.environ.get('RELAY_PORT', 443))
RELAY_SCHEME = os.environ.get('RELAY_SCHEME', 'https')
3
Create relay.py Client Utility
import pusher
from django.conf import settings
relay_client = pusher.Pusher(
app_id=settings.RELAY_APP_ID,
key=settings.RELAY_APP_KEY,
secret=settings.RELAY_APP_SECRET,
host=settings.RELAY_HOST,
port=settings.RELAY_PORT,
ssl=(settings.RELAY_SCHEME == 'https'),
)
4
Trigger from a Django View
from relay import relay_client
from django.http import JsonResponse
def send_message(request):
message = request.POST.get('message')
relay_client.trigger('public-feed', 'message.sent', {
'message': message,
'user': request.user.username,
})
return JsonResponse({'status': 'sent'})
5
Trigger from a Celery Task
from celery import shared_task
from relay import relay_client
@shared_task
def notify_users(message):
relay_client.trigger('public-feed', 'notification', {
'message': message,
})
6
Connect the Frontend
On the client side, use the Pusher JS client to subscribe to channels and listen for events. Point the client at your Relay host and app key. See the Next.js guide for a full frontend example.
The Pusher Python SDK supports custom hosts natively. Relay is fully compatible with all Pusher SDK methods including batch triggers and channel queries.
Ready to skip the server setup? Relay Cloud gives you a production WebSocket server instantly. Start free, upgrade when you grow.
Start free →