Skip to main content

Easy Channels

Lightweight framework for quickly making socket consumers using Django and DjangoChannels.

Installing

pip install django-easy-channels

Socket Example

Backend

from easy_channels import JSONConsumer


class ChatConsumer(JSONConsumer):
    # Socket connects
    def on_connect(self):
        # gets name from url
        self.name = self.scope['url_route']['kwargs']['name']

        # Adds socket and consumer to group chatroom
        self.group_add('chatroom')

        # Accepts socket connection
        self.accept()

    # Called when consumer receives a message with the event broadcast_message
    def on_broadcast_message(self, event):
        payload = {
            'message': event['message'],
            'from': self.name
        }

        # Sends this message to all connected sockets in the 'chatroom' group (not consumers)
        await self.group_send(
            'chatroom', # group
            'message', # event name
            payload # data
        )

Frontend

const messages = [];
const socket = new WebSocket("wss://YOUR_URL/chat/joselito");

// Called when socket receives a message
socket.onmessage = function (message) {
  switch (message.event) {
    case "message":
      messages.push({
        message: message.message,
        from: message.from,
      });
  }
};

socket.send(
  JSON.stringify({
    event: "broadcast_message", // Calls "on_broadcast()" function in consumer
    message: "Hello World!", // Can be acessed in bachend using event['message']
  })
);

Adding to Route

This JSONConsumer can be added to Django Channels route in the same way of the original consumers.

from django.urls import re_path

from .consumers import ChatConsumer

websocket_urlpatterns = [
    re_path(r'^ws/chat/(?P<name>\w+)/', consumers.ChatConsumer),
]

Communicating Between Consumers

Sometimes you want your consumers to talk with each other without sending data to the front end.

For example, we can make a consumer A notify a consumer B that it needs to update its frontend information without this confidental data passing through consumer A.

class ConsumerA(JSONConsumer):
    def on_connect(self):
        self.group_add('groupA')

    def on_notify(self):
        sensitive_data = get_some_data()
        self.group_send(
            'groupA',
            'notify',
            sensitive_data
        )

class ConsumerB(JSONConsumer):
    def on_connect(self):
        self.group_add('groupB')

    def on_some_event(self):
        # Calls 'on_notify()' in all consumers added to groupA
        self.group_call_event(
            'groupA',
            'notify'
        )

Middleware Example

You can create custom middlewares that will be run before the on_connect function or whenever a message is received.

The code below will automatically gather the chat user name from url.

from easy_channels.middleware import ConsumerMiddleware

class UserGatherMiddleware(ConsumerMiddleware):

    # Called before the consumer's 'on_connect()'
    def on_connect(self):
        # This middleware has complete access to the consumer in the self.consumer attribute
        self.consumer.name = self.scope['url_route']['kwargs']['name']

To the middleware to work with the consumer we must pass it.

class ChatConsumer(JSONConsumer):
    middlewares = [UserGatherMiddleware]

    def on_connect(self):
        print(self.name) # Will print the user name
    ...

Metadata

Release files for django-easy-channels 0.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-easy-channels 0.0.1
File Size Uploaded Provenance
django-easy-channels-0.0.1.tar.gz 3.9 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for django-easy-channels 0.0.1
File Interpreter ABI Platform
django_easy_channels-0.0.1-py3-none-any.whl Python 3 none any Details

Total release size: 8.1 kB

Release files / django-easy-channels-0.0.1.tar.gz

Download URL django-easy-channels-0.0.1.tar.gz
Size 3.9 kB
Tags Source
SHA-256 checksum
How to use checksums
d1a11e75ec0eda49cfac9def347b63236283238fcf3a5a690d0dcd10daf34def
BLAKE2b-256 checksum
How to use checksums
46c48c920e5dc6ed85442e6acf11f96d53baf856489e8f160214e634f2445a41
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/50.3.0 requests-toolbelt/0.9.1 tqdm/4.50.2 CPython/3.8.5

Release files / django_easy_channels-0.0.1-py3-none-any.whl

Download URL django_easy_channels-0.0.1-py3-none-any.whl
Size 4.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
654134b4c4f91238fff76dcc0d0a3b3449533adc286312a0bd8bc713dc8568d0
BLAKE2b-256 checksum
How to use checksums
81c7eac40463a0a9f87f598bb0f1de81eb4496efbfd1edfa69dff07656088cf3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/50.3.0 requests-toolbelt/0.9.1 tqdm/4.50.2 CPython/3.8.5

Security for django-easy-channels 0.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Release history Release notifications | RSS feed

This release

0.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page