Skip to main content

A thin wrapper around channels consumer to make things EASY

Project description

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.

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

channels-easy-0.3.0.tar.gz (5.6 kB view details)

Uploaded Source

Built Distribution

channels_easy-0.3.0-py3-none-any.whl (5.4 kB view details)

Uploaded Python 3

File details

Details for the file channels-easy-0.3.0.tar.gz.

File metadata

  • Download URL: channels-easy-0.3.0.tar.gz
  • Upload date:
  • Size: 5.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.12 CPython/3.9.9 Linux/5.11.0-1025-azure

File hashes

Hashes for channels-easy-0.3.0.tar.gz
Algorithm Hash digest
SHA256 531ac814fec47ec8c4d9f58da204c7247129ed4bfdc415a006125a3516377c1c
MD5 5d6587bc069578eed93db8429cd6c2b7
BLAKE2b-256 3bf67b5b34f147479755adde5b53fed4dacfae591292ee836e60a74d4700bf0f

See more details on using hashes here.

File details

Details for the file channels_easy-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: channels_easy-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 5.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.12 CPython/3.9.9 Linux/5.11.0-1025-azure

File hashes

Hashes for channels_easy-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 37614cf6847032bece2c78ad786a2fac7edbf4a31fab3a0eadca99f169bbc419
MD5 289b86061cd03bfe6ba053619b6700b3
BLAKE2b-256 968e3bcb08b6c472613b24b04da998cd55c3a27210ab165436b267c6e2eba5d9

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