Skip to main content
PyPI Code Coverage Test Checked with mypy Checked with pyright Interrogate Badge

The missing toolkit for Django Channels — authentication, logging, structured messaging, and more.

Installation

pip install chanx

For complete documentation, visit chanx docs.

Introduction

Django Channels provides excellent WebSocket support for Django applications, but leaves gaps in authentication, structured messaging, and developer tooling. Chanx fills these gaps with a comprehensive toolkit that makes building WebSocket applications simpler and more maintainable.

Key Features

  • REST Framework Integration: Use DRF authentication and permission classes with WebSockets

  • Structured Messaging: Type-safe message handling with Pydantic validation and generic type parameters

  • WebSocket Playground: Interactive UI for testing WebSocket endpoints

  • Group Management: Simplified pub/sub messaging with automatic group handling

  • Typed Channel Events: Type-safe channel layer events

  • Channels-friendly Routing: Django-like path, re_path, and include functions designed specifically for WebSocket routing

  • Comprehensive Logging: Structured logging for WebSocket connections and messages

  • Error Handling: Robust error reporting and client feedback

  • Testing Utilities: Specialized tools for testing WebSocket consumers

  • Multi-user Testing Support: Test group broadcasting and concurrent connections

  • Object-level Permissions: Support for DRF object-level permission checks

  • Full Type Hints: Complete mypy and pyright support for better IDE integration and type safety

Core Components

  • AsyncJsonWebsocketConsumer: Base consumer with authentication, structured messaging, and typed events

  • ChanxWebsocketAuthenticator: Bridges WebSockets with DRF authentication

  • Message System: Type-safe message classes with automatic validation and generic type parameters

  • Channel Event System: Type-safe channel layer events

  • WebSocket Routing: Django-style routing functions (path, re_path, include) optimized for Channels

  • WebSocketTestCase: Test utilities for WebSocket consumers

  • Generic Type Safety: Compile-time type checking with generic parameters for messages, events, and models

Using Generic Type Parameters

AsyncJsonWebsocketConsumer uses three generic type parameters for improved type safety:

class AsyncJsonWebsocketConsumer[IC, Event, M]:
    """
    Typed WebSocket consumer with three generic parameters:

    IC: Incoming message type (required) - Union of BaseMessage subclasses
    Event: Channel event type (optional) - Union of BaseChannelEvent subclasses or None
    M: Model type (optional) - Django model for object-level permissions
    """

You can use these parameters in different combinations:

# Minimal usage - just specify incoming message type
class SimpleConsumer(AsyncJsonWebsocketConsumer[PingMessage]):
    async def receive_message(self, message: PingMessage, **kwargs: Any) -> None:
        # message is properly typed as PingMessage
        ...

# With incoming messages and events
class EventConsumer(AsyncJsonWebsocketConsumer[ChatMessage, ChatEvent]):
    async def receive_message(self, message: ChatMessage, **kwargs: Any) -> None:
        # Handle incoming messages
        ...

    async def receive_event(self, event: ChatEvent) -> None:
        # Handle typed events using pattern matching
        match event:
            case NotifyEvent():
                # Process the notification event
                await self.send_message(ResponseMessage(payload=event.payload))
            case _:
                pass

# With group messaging
class GroupConsumer(AsyncJsonWebsocketConsumer[ChatMessage]):
    async def receive_message(self, message: ChatMessage, **kwargs: Any) -> None:
        # Send typed group messages using send_group_message
        group_msg = MemberMessage(payload={"content": "Hello group!"})
        await self.send_group_message(group_msg)

# Complete example with all generic parameters
class ChatConsumer(AsyncJsonWebsocketConsumer[ChatMessage, ChatEvent, Room]):
    # Room is used for object-level permissions
    queryset = Room.objects.all()

    async def build_groups(self) -> list[str]:
        # self.obj is typed as Room
        return [f"room_{self.obj.id}"]

Making Parameters Optional

For parameters you don’t need, use None:

# No events, with model
class ModelConsumer(AsyncJsonWebsocketConsumer[ChatMessage, None, Room]):
    ...

# With events, no model
class EventOnlyConsumer(AsyncJsonWebsocketConsumer[ChatMessage, ChatEvent]):
    ...

Configuration

Chanx can be configured through the CHANX dictionary in your Django settings. Below is a complete list of available settings with their default values and descriptions:

# settings.py
CHANX = {
    # Message configuration
    'MESSAGE_ACTION_KEY': 'action',  # Key name for action field in messages
    'CAMELIZE': False,  # Whether to camelize/decamelize messages for JavaScript clients

    # Completion messages
    'SEND_COMPLETION': False,  # Whether to send completion message after processing messages

    # Messaging behavior
    'SEND_MESSAGE_IMMEDIATELY': True,  # Whether to yield control after sending messages
    'SEND_AUTHENTICATION_MESSAGE': True,  # Whether to send auth status after connection

    # Logging configuration
    'LOG_RECEIVED_MESSAGE': True,  # Whether to log received messages
    'LOG_SENT_MESSAGE': True,  # Whether to log sent messages
    'LOG_IGNORED_ACTIONS': [],  # Message actions that should not be logged

    # Playground configuration
    'WEBSOCKET_BASE_URL': 'ws://localhost:8000'  # Default WebSocket URL for discovery
}

WebSocket Routing

Chanx provides Django-style routing functions specifically designed for WebSocket applications. These functions work similarly to Django’s URL routing but are optimized for Channels and ASGI applications.

Key principles:

  • Use chanx.routing for WebSocket routes in your routing.py files

  • Use django.urls for HTTP routes in your urls.py files

  • Maintain clear separation between HTTP and WebSocket routing

Available functions:

  • path(): Create URL patterns with path converters (e.g., '<int:id>/')

  • re_path(): Create URL patterns with regular expressions

  • include(): Include routing patterns from other modules

Example routing setup:

# app/routing.py
from chanx.routing import path, re_path
from . import consumers

router = URLRouter([
    path("", consumers.MyConsumer.as_asgi()),
    path("room/<str:room_name>/", consumers.RoomConsumer.as_asgi()),
    re_path(r"^admin/(?P<id>\d+)/$", consumers.AdminConsumer.as_asgi()),
])

# project/routing.py
from chanx.routing import include, path
from channels.routing import URLRouter

router = URLRouter([
    path("ws/", URLRouter([
        path("app/", include("app.routing")),
        path("chat/", include("chat.routing")),
    ])),
])

WebSocket Playground

Add the playground to your URLs and explore your WebSocket endpoints interactively:

urlpatterns = [
    path('playground/', include('chanx.playground.urls')),
]

Visit /playground/websocket/ to test your endpoints without writing JavaScript.

Complete Example Project

For a full production-ready implementation with advanced patterns and deployment configurations, check out the complete example project:

GitHub Repository: chanx-example

This repository demonstrates:

  • Production deployment configurations

  • Advanced authentication patterns

  • Group messaging and channel events

  • Comprehensive testing strategies

  • Real-world usage patterns

Learn More

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chanx-0.13.1.tar.gz (47.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

chanx-0.13.1-py3-none-any.whl (60.6 kB view details)

Uploaded Python 3

File details

Details for the file chanx-0.13.1.tar.gz.

File metadata

  • Download URL: chanx-0.13.1.tar.gz
  • Upload date:
  • Size: 47.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for chanx-0.13.1.tar.gz
Algorithm Hash digest
SHA256 80052800fa2a4139472c8d06e520fac5802376c16e7459b1ffc5fa383125e1b5
MD5 84ab9336deae4071a7e9f381880ec4bd
BLAKE2b-256 2626182eb6c0c1272efeddd7e436daaac1342ea8626e32bf4299683327796cac

See more details on using hashes here.

Provenance

The following attestation bundles were made for chanx-0.13.1.tar.gz:

Publisher: publish.yml on huynguyengl99/chanx

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file chanx-0.13.1-py3-none-any.whl.

File metadata

  • Download URL: chanx-0.13.1-py3-none-any.whl
  • Upload date:
  • Size: 60.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for chanx-0.13.1-py3-none-any.whl
Algorithm Hash digest
SHA256 4f927457af4742f74c50d0591ffbd14c07b6e28d6fcf1d5e977d74631c1c7503
MD5 4dbf465f010f80196d9e99fec79f421b
BLAKE2b-256 2c87712ac9b4242b81e766f2ce4596909b4d8c2e979269e6b14ff4935ffd001a

See more details on using hashes here.

Provenance

The following attestation bundles were made for chanx-0.13.1-py3-none-any.whl:

Publisher: publish.yml on huynguyengl99/chanx

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page