Skip to main content

This package provides Rails Action Cable support to Django

Project description

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.

Project details


Download files

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

Source Distribution

django_actioncable-1.0.4.tar.gz (4.5 kB view details)

Uploaded Source

Built Distribution

django_actioncable-1.0.4-py3-none-any.whl (5.7 kB view details)

Uploaded Python 3

File details

Details for the file django_actioncable-1.0.4.tar.gz.

File metadata

  • Download URL: django_actioncable-1.0.4.tar.gz
  • Upload date:
  • Size: 4.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.7

File hashes

Hashes for django_actioncable-1.0.4.tar.gz
Algorithm Hash digest
SHA256 0b24111b27e7aa6ed3cad1acaca47b3537dc73d49c266c5c4b2b42b079c2d6bb
MD5 70c17b8234fc78a9efce33bb0486e927
BLAKE2b-256 a8d7e203e37e9cc574c58bb4e824897743db985038602c2acaa1ecda2512a893

See more details on using hashes here.

File details

Details for the file django_actioncable-1.0.4-py3-none-any.whl.

File metadata

File hashes

Hashes for django_actioncable-1.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 c7becceb29a6748266a8b35b426103506549d4d759c031ef0468a09f61161524
MD5 b48b5233cfaa6736c7cad3fd19f4141c
BLAKE2b-256 63b872af5276ea41e4c60cc785e878f121b36a07c3658867c81ae7294dec53b3

See more details on using hashes here.

Supported by

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