Skip to main content

README

This package provides Rails Action Cable support to Django Channels.

Install

Please make sure Django channels is already working in Django project before installing this package.

$ pip install django-actioncable

In the asgi.py, we have code like this

import os

from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application

from django_app.core import routing

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_app.settings")

application = ProtocolTypeRouter(
    {
        "http": get_asgi_application(), 
        "websocket": URLRouter(routing.urlpatterns)
    }
)

Notes:

  1. The websocket protocol would be handled by URLRouter(routing.urlpatterns)

In the routing file, we add below code:

from actioncable import ActionCableConsumer


urlpatterns = [
    path("cable", ActionCableConsumer.as_asgi()),
]

Notes:

  1. So all the Websocket requests sent to ws://localhost:8000/cable would be handled by ActionCableConsumer
  2. The ActionCableConsumer would then dispatch the request to the corresponding channel class.

We can add below code to the routing file to register the channel class.

from actioncable import ActionCableConsumer, CableChannel, cable_channel_register


@cable_channel_register
class ChatChannel(CableChannel):

    def __init__(self, consumer: ActionCableConsumer, identifier_key, params=None):
        self.params = params if params else {}
        self.identifier_key = identifier_key
        self.consumer = consumer
        self.group_name = None

    async def subscribe(self):
        self.group_name = f"chat_{self.params['pk']}"
        await self.consumer.subscribe_group(self.group_name, self)

    async def unsubscribe(self):
        await self.consumer.unsubscribe_group(self.group_name, self)
  1. We create a ChatChannel, which inherits from the CableChannel.
  2. The cable_channel_register decorator would register the ChatChannel class to the ActionCableConsumer.
  3. In the subscribe callback method, we get the room pk from the self.params dict and subscribe the channel to the group chat_{pk}.
  4. In the unsubscribe callback method, we unsubscribe the channel from the group.

HTML

<!DOCTYPE html>
<html>
<head>
  <title>ActionCable Example</title>
</head>
<body>
<div id="messages"></div>

<script src="https://cdn.jsdelivr.net/npm/@rails/actioncable@7.1.2/app/assets/javascripts/actioncable.js"></script>
<script>
  document.addEventListener("DOMContentLoaded", function () {
    // Create a consumer object to connect to the ActionCable server
    const cable = ActionCable.createConsumer();

    // Define a channel and its corresponding functions
    const channel = cable.subscriptions.create({channel: "ChatChannel", pk: "1"}, {
      connected() {
        console.log("Connected to the chat channel.");
      },

      disconnected() {
        console.log("Disconnected from the chat channel.");
      },

      received(data) {
        // Display the received message
        const messagesDiv = document.getElementById("messages");
        const messageDiv = document.createElement("div");
        messageDiv.innerText = data;
        messagesDiv.appendChild(messageDiv);
      }
    });
  });
</script>

</body>
</html>

Notes:

  1. We use the ActionCable.createConsumer() to create a consumer object to connect to the ActionCable server.
  2. The channe is ChatChannel, so the ChatChannel we just created will be used to handle the request.
  3. In the client, we can pass room pk to the ChatChannel by pk: "1", and in the backend we can get it in the self.params
  4. In this case, the channel will subscribe to the chat_1 group.

Test

Launch Django shell, and run below code:

from actioncable import cable_broadcast

cable_broadcast("chat_1", message="Hello World")

You should be able to see the message appear on the web page.

cable_broadcast is a wrapper of Django Channel async_to_sync(channel_layer.group_send) method call, we can use it in Django view or external process such as Celery worker.

The message value can also be Python dict, and in javascript we can get it in the data parameter of the received callback method.

Metadata

Release files for django-actioncable 1.0.4

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-actioncable 1.0.4
File Size Uploaded Provenance Actions
django_actioncable-1.0.4.tar.gz 4.5 kB Without provenance Details for django_actioncable-1.0.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-actioncable 1.0.4
File Interpreter ABI Platform Actions
django_actioncable-1.0.4-py3-none-any.whl Python 3 none any Details for django_actioncable-1.0.4-py3-none-any.whl

Total release size: 10.2 kB

Release files / django_actioncable-1.0.4.tar.gz

Download URL django_actioncable-1.0.4.tar.gz
Size 4.5 kB
Tags Source
SHA-256 checksum
How to use checksums
0b24111b27e7aa6ed3cad1acaca47b3537dc73d49c266c5c4b2b42b079c2d6bb
BLAKE2b-256 checksum
How to use checksums
a8d7e203e37e9cc574c58bb4e824897743db985038602c2acaa1ecda2512a893
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.7

Release files / django_actioncable-1.0.4-py3-none-any.whl

Download URL django_actioncable-1.0.4-py3-none-any.whl
Size 5.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c7becceb29a6748266a8b35b426103506549d4d759c031ef0468a09f61161524
BLAKE2b-256 checksum
How to use checksums
63b872af5276ea41e4c60cc785e878f121b36a07c3658867c81ae7294dec53b3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.7

Security for django-actioncable 1.0.4

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.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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