django_sockets

Django Sockets

PyPI version License: MIT

Simplified Django WebSocket integrations designed for speed, flexibility, and cloud-cache scaling (Valkey/Redis). Works seamlessly on single, distributed, or serverless cache setups.

  • ASGI Server Compatibility: Compatible with any standard ASGI server (such as Uvicorn, Daphne, or Hypercorn).
  • Multi-Framework: Can also be used in non-Django applications (Flask, FastAPI, or raw Python) for lightweight Pub/Sub messaging.

Key Features

  • Cache-Backed Pub/Sub: Async broadcasting using Redis or Valkey.
  • Simplified Middleware: Simple authentication wrappers for Django Sessions and Django Rest Framework (DRF) Tokens.
  • ASGI Native: Implements standard ProtocolTypeRouter and URLRouter for minimal overhead.
  • Subprotocol Auth: Supports secure token-based authentication via the Sec-WebSocket-Protocol header.
  • Minimal Boilerplate: Define a class with connect, receive, and disconnect hooks and you're ready to go.

Installation & Setup

pip install django_sockets

Valkey/Redis Setup

To use broadcasting and pub/sub features, you need a Redis or Valkey cache server:

# Start a local Valkey cache via Docker
docker run -d -p 6379:6379 --name django_sockets_cache valkey/valkey:7

Quickstart (Django)

1. Define your Socket Server

Create a ws.py in your Django app:

from django.urls import path
from django_sockets.sockets import BaseSocketServer
from django_sockets.middleware import SessionAuthMiddleware
from django_sockets.utils import URLRouter


class MyCounterSocket(BaseSocketServer):
    def configure(self):
        # Configure cache hosts (optional, needed for pub/sub)
        self.hosts = [{"address": "redis://localhost:6379"}]

    def connect(self):
        # Scope-aware user extraction
        self.channel_id = f"user_{self.scope['user'].id}"
        self.subscribe(self.channel_id)

    def receive(self, data):
        # Broadcast incoming JSON to all subscribers of this channel
        self.broadcast(self.channel_id, data)


# Wrap with authentication middleware and URL routing
websocket_application = SessionAuthMiddleware(
    URLRouter(
        [
            path("ws/counter/", MyCounterSocket.as_asgi),
        ]
    )
)

2. Configure ASGI Entrypoint

In your Django asgi.py (ensure imports are ordered correctly to allow proper Django initialization):

import os
from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
django_asgi_app = get_asgi_application()

# Import django_sockets after Django initialization
from django_sockets.utils import ProtocolTypeRouter
from .ws import websocket_application

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": websocket_application,
    }
)

Running the ASGI Server

You can run your Django ASGI application using any ASGI-compliant web server:

Uvicorn

pip install uvicorn
uvicorn myapp.asgi:application --reload

Daphne

pip install daphne
daphne -p 8000 myapp.asgi:application

Hypercorn

pip install hypercorn
hypercorn myapp.asgi:application --bind 127.0.0.1:8000

Guides & Examples

We provide detailed step-by-step tutorials and code samples:

  • Step-by-Step Django Tutorial (TUTORIAL.md): Build a fully-featured, user-scoped real-time counter using session or DRF token authentication from scratch.
  • Examples Directory:
    • examples/django/myapp: Full project showing standard Django Session authentication.
    • examples/django/myapp_drf: Full project showing DRF Token authentication.
    • examples/without_django: Standalone python pub/sub without Django dependencies.

Non-Django Usage (Flask, FastAPI, Raw Python)

django_sockets can run without Django's registry:

1. Broadcaster (Sending from Flask/FastAPI)

Publish events from any HTTP route to WebSocket clients:

from flask import Flask, request
from django_sockets.broadcaster import Broadcaster

app = Flask(__name__)
broadcaster = Broadcaster(hosts=[{"address": "redis://localhost:6379"}])


@app.route("/alert", methods=["POST"])
def send_alert():
    broadcaster.broadcast("alerts_channel", request.json)
    return {"status": "Alert sent"}

2. Running a Pure ASGI Server

Initialize BaseSocketServer manually in custom ASGI configurations or raw Python scripts:

import asyncio
from django_sockets.sockets import BaseSocketServer


async def my_send_handler(data):
    print("Sent:", data)


receive_queue = asyncio.Queue()
socket_server = BaseSocketServer(
    scope={},
    receive=receive_queue.get,
    send=my_send_handler,
    hosts=[{"address": "redis://localhost:6379"}],
)
socket_server.start_listeners()

Development & Testing

Run the full pytest suite:

uv run pytest

For manual testing, manage the local Docker Valkey instance using:

uv run python utils/redis_start.py
# Run your manual scripts (e.g. uv run test/06_django_integration.py)
uv run python utils/redis_stop.py

Attributions

Some of the code in this repository is formed similarly to or inspired by channels_redis and django_channels. Many thanks to their authors for the original work and inspiration.

  1"""
  2# Django Sockets
  3
  4[![PyPI version](https://badge.fury.io/py/django_sockets.svg)](https://badge.fury.io/py/django_sockets)
  5[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
  6
  7Simplified Django WebSocket integrations designed for speed, flexibility, and cloud-cache scaling (Valkey/Redis). Works seamlessly on single, distributed, or serverless cache setups.
  8
  9- **ASGI Server Compatibility**: Compatible with **any standard ASGI server** (such as Uvicorn, Daphne, or Hypercorn).
 10- **Multi-Framework**: Can also be used in **non-Django applications** (Flask, FastAPI, or raw Python) for lightweight Pub/Sub messaging.
 11
 12---
 13
 14## Key Features
 15
 16- **Cache-Backed Pub/Sub**: Async broadcasting using Redis or Valkey.
 17- **Simplified Middleware**: Simple authentication wrappers for Django Sessions and Django Rest Framework (DRF) Tokens.
 18- **ASGI Native**: Implements standard `ProtocolTypeRouter` and `URLRouter` for minimal overhead.
 19- **Subprotocol Auth**: Supports secure token-based authentication via the `Sec-WebSocket-Protocol` header.
 20- **Minimal Boilerplate**: Define a class with `connect`, `receive`, and `disconnect` hooks and you're ready to go.
 21
 22---
 23
 24## Installation & Setup
 25
 26```bash
 27pip install django_sockets
 28```
 29
 30### Valkey/Redis Setup
 31To use broadcasting and pub/sub features, you need a Redis or Valkey cache server:
 32```bash
 33# Start a local Valkey cache via Docker
 34docker run -d -p 6379:6379 --name django_sockets_cache valkey/valkey:7
 35```
 36
 37---
 38
 39## Quickstart (Django)
 40
 41### 1. Define your Socket Server
 42Create a `ws.py` in your Django app:
 43
 44```python
 45from django.urls import path
 46from django_sockets.sockets import BaseSocketServer
 47from django_sockets.middleware import SessionAuthMiddleware
 48from django_sockets.utils import URLRouter
 49
 50
 51class MyCounterSocket(BaseSocketServer):
 52    def configure(self):
 53        # Configure cache hosts (optional, needed for pub/sub)
 54        self.hosts = [{"address": "redis://localhost:6379"}]
 55
 56    def connect(self):
 57        # Scope-aware user extraction
 58        self.channel_id = f"user_{self.scope['user'].id}"
 59        self.subscribe(self.channel_id)
 60
 61    def receive(self, data):
 62        # Broadcast incoming JSON to all subscribers of this channel
 63        self.broadcast(self.channel_id, data)
 64
 65
 66# Wrap with authentication middleware and URL routing
 67websocket_application = SessionAuthMiddleware(
 68    URLRouter(
 69        [
 70            path("ws/counter/", MyCounterSocket.as_asgi),
 71        ]
 72    )
 73)
 74```
 75
 76### 2. Configure ASGI Entrypoint
 77In your Django `asgi.py` (ensure imports are ordered correctly to allow proper Django initialization):
 78
 79```python
 80import os
 81from django.core.asgi import get_asgi_application
 82
 83os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
 84django_asgi_app = get_asgi_application()
 85
 86# Import django_sockets after Django initialization
 87from django_sockets.utils import ProtocolTypeRouter
 88from .ws import websocket_application
 89
 90application = ProtocolTypeRouter(
 91    {
 92        "http": django_asgi_app,
 93        "websocket": websocket_application,
 94    }
 95)
 96```
 97
 98---
 99
100## Running the ASGI Server
101
102You can run your Django ASGI application using any ASGI-compliant web server:
103
104### Uvicorn
105```bash
106pip install uvicorn
107uvicorn myapp.asgi:application --reload
108```
109
110### Daphne
111```bash
112pip install daphne
113daphne -p 8000 myapp.asgi:application
114```
115
116### Hypercorn
117```bash
118pip install hypercorn
119hypercorn myapp.asgi:application --bind 127.0.0.1:8000
120```
121
122---
123
124## Guides & Examples
125
126We provide detailed step-by-step tutorials and code samples:
127
128- **[Step-by-Step Django Tutorial (TUTORIAL.md)](TUTORIAL.md)**: Build a fully-featured, user-scoped real-time counter using session or DRF token authentication from scratch.
129- **[Examples Directory](examples/)**:
130  - `examples/django/myapp`: Full project showing standard Django Session authentication.
131  - `examples/django/myapp_drf`: Full project showing DRF Token authentication.
132  - `examples/without_django`: Standalone python pub/sub without Django dependencies.
133
134---
135
136## Non-Django Usage (Flask, FastAPI, Raw Python)
137
138`django_sockets` can run without Django's registry:
139
140### 1. Broadcaster (Sending from Flask/FastAPI)
141Publish events from any HTTP route to WebSocket clients:
142```python
143from flask import Flask, request
144from django_sockets.broadcaster import Broadcaster
145
146app = Flask(__name__)
147broadcaster = Broadcaster(hosts=[{"address": "redis://localhost:6379"}])
148
149
150@app.route("/alert", methods=["POST"])
151def send_alert():
152    broadcaster.broadcast("alerts_channel", request.json)
153    return {"status": "Alert sent"}
154```
155
156### 2. Running a Pure ASGI Server
157Initialize `BaseSocketServer` manually in custom ASGI configurations or raw Python scripts:
158```python
159import asyncio
160from django_sockets.sockets import BaseSocketServer
161
162
163async def my_send_handler(data):
164    print("Sent:", data)
165
166
167receive_queue = asyncio.Queue()
168socket_server = BaseSocketServer(
169    scope={},
170    receive=receive_queue.get,
171    send=my_send_handler,
172    hosts=[{"address": "redis://localhost:6379"}],
173)
174socket_server.start_listeners()
175```
176
177---
178
179## Development & Testing
180
181Run the full pytest suite:
182```bash
183uv run pytest
184```
185
186For manual testing, manage the local Docker Valkey instance using:
187```bash
188uv run python utils/redis_start.py
189# Run your manual scripts (e.g. uv run test/06_django_integration.py)
190uv run python utils/redis_stop.py
191```
192
193---
194
195## Attributions
196
197Some of the code in this repository is formed similarly to or inspired by `channels_redis` and `django_channels`. Many thanks to their authors for the original work and inspiration.
198"""