Skip to content

namantam1/channels-easy

Repository files navigation

codecov Release Test Code style: black

Channels Easy

A thin wrapper around channel consumers to make things EASY

Note: This library currently support only text data which is JSON serializable.

What problem does this library solve?

This library simplifies two tasks for now

  1. Parse incoming text data as JSON and vice versa.
  2. Generate event on the basis of type passed from client side.

Table of Contents

Installation

To get the latest stable release from PyPi

pip install channels-easy

As channels-easy is a thin wrapper around channels so channels must be in your INSTALLED_APPS in settings.py.

INSTALLED_APPS = (
    ...,
    'channels',
)

Example

All the naming convention used to implement this library is inspired from socket.io to make server implementation simple.

Get full example project here.

Server side

# consumers.py
from channels_easy.generic import AsyncWebsocketConsumer


class NewConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        # join room on connect
        await self.join("room1")
        await self.accept()

    async def disconnect(self, close_code):
        # Leave room on disconnect
        await self.leave("room1")

    async def on_message(self, data):
        print("message from client", data)
        # output:
        # message from client {'text': 'hello'}

        await self.emit("message", {"message": "hello from server"}, "room1")

Client side

// client.js
const socket = new WebSocket("ws://localhost:8000/ws/test/");

socket.onmessage = function ({ data }) {
    const parsed_data = JSON.parse(data);
    console.log(parsed_data);
    // output:
    // {
    //     data: {message: 'hello from server'}
    //     type: "message"
    // }
};

socket.onopen = () => {
    console.log("websocket connected...");

    // send message from client after connected
    // send with type `message` to receive from subscribed
    // `on_message` event on server side
    socket.send(
        JSON.stringify({
            type: "message",
            data: {
                text: "hello",
            },
        })
    );
};

API Usage

Subscribing to events We can simply subscribe to a message type as

def on_<type>(self, data):
    ...
    pass

so if client send data as

{
    "type": "message",
    "data": "Hello!"
}

We can subscribe to message event as

def on_message(self, data):
    ...
    pass

Emitting Message

We can emit message to client using same schema that we used above

def on_message(self, data):
    ...
    # some code here
    ...

    self.emit(
        "message",          # type
        {"text": "hello"},  # message dict | str | int | list
        ["room1"],          # room list or string
    )

Check all APIs here.

Contribute

If you want to contribute to this project, please perform the following steps

# Fork this repository
# Clone your fork
poetry install

git checkout -b feature_branch master
# Implement your feature and tests
git add . && git commit
git push -u origin feature_branch
# Send us a pull request for your feature branch

In order to run the tests, simply execute poetry run pytest. This will run test created inside test directory.