Skip to content

Commit

Permalink
Bump version 0.3.0
Browse files Browse the repository at this point in the history
  • Loading branch information
namantam1 committed Jan 13, 2022
1 parent f128eb4 commit e62132a
Show file tree
Hide file tree
Showing 10 changed files with 112 additions and 61 deletions.
12 changes: 5 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ 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](#installation)
- [Example](#example)
- [API Usage](#api-usage)
Expand All @@ -26,11 +29,6 @@ To get the latest stable release from PyPi
```bash
pip install channels-easy
```
To get the latest commit from GitHub

```bash
pip install -e git+git://github.com/namantam1/channels-easy.git#egg=channels-easy
```

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

Expand Down Expand Up @@ -68,7 +66,7 @@ class NewConsumer(AsyncWebsocketConsumer):
# output:
# message from client {'text': 'hello'}

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

```

Expand Down Expand Up @@ -144,8 +142,8 @@ def on_message(self, data):

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

Expand Down
2 changes: 1 addition & 1 deletion channels_easy/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.2.3"
__version__ = "0.3.0"
78 changes: 42 additions & 36 deletions channels_easy/generic.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from logging import Logger
from typing import Iterable, Union
from xmlrpc.client import boolean

from channels.generic.websocket import AsyncWebsocketConsumer as BaseConsumer

Expand All @@ -16,50 +17,56 @@ def get_handler_name(typ):


class AsyncWebsocketConsumer(BaseConsumer):
async def close_with_error(self, error_data, code=None):
"""Close socket after emitting error message
Args:
error_data (Any): Any json serializable data
code (int): Close code pass to close
"""
await self.emit_error(error_data)
await self.close(code)

async def emit(self, typ: str, to: Union[str, int, Iterable], data):
async def emit(
self,
typ: str,
data,
to: Union[str, int, Iterable] = None,
close: Union[int, boolean] = None,
):
"""Send message to given rooms
Args:
typ (str): message type
to (Union[str, Iterable]): List of rooms or a single room
data (Any): data which is json serializable
to (Union[str, int, Iterable], optional): List of rooms or a single room
close (Union[int, boolean], optional): Boolean or error code, If passed \
close socket after emitting message
*Note*: If `to` is not passed, emit message to self user
"""
if not isinstance(to, (list, tuple, set)):
to = [to]
# send to each channels
for group in set(to):
await self.channel_layer.group_send(
str(group),
{
"type": "send_message",
"message": {"type": typ, "data": data},
},
)

async def emit_error(self, data):
text_data = json.dumps({"type": typ, "data": data})

if to is None:
await self.send(text_data=text_data)
else:
if not isinstance(to, (list, tuple, set)):
to = [to]
# send to each group
for group in set(to):
await self.channel_layer.group_send(
str(group),
{
"type": "send_message",
"text_data": text_data,
},
)

if close is not None:
if isinstance(close, boolean):
await self.close()
else:
await self.close(close)

async def emit_error(self, data, close: Union[int, boolean] = None):
"""Emit message with `error` type and data
Args:
data (Any): Any json serializable value
close (Union[int, boolean], optional): Boolean or error code. If passed \
close socket after emitting error
"""
await self.send(
json.dumps(
dict(
type="error",
data=data,
)
)
)
await self.emit("error", data, close=close)

async def join(self, room: Union[str, int, Iterable]):
"""Join room with passed name
Expand Down Expand Up @@ -114,7 +121,6 @@ async def receive(self, text_data):

async def send_message(self, event):
"""
Send message to client
Send message down to Websocket
"""
# send a message down to client
await self.send(json.dumps(event["message"]))
await self.send(text_data=event["text_data"])
1 change: 0 additions & 1 deletion docs/apis.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
## ::: channels_easy.generic.AsyncWebsocketConsumer
selection:
members:
- close_with_error
- emit
- emit_error
- join
Expand Down
18 changes: 10 additions & 8 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,16 @@ A thin wrapper around channel consumers to make things **EASY**
**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](#installation)
- [Example](#example)
- [API Usage](#api-usage)
- [Contribute](#contribute)

## Installation

Expand All @@ -22,11 +29,6 @@ To get the latest stable release from PyPi
```bash
pip install channels-easy
```
To get the latest commit from GitHub

```bash
pip install -e git+git://github.com/namantam1/channels-easy.git#egg=channels-easy
```

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

Expand All @@ -41,7 +43,7 @@ INSTALLED_APPS = (

All the naming convention used to implement this library is inspired from [socket.io](https://socket.io/) to make server implementation simple.

Get full example project [here](https://github.com/namantam1/channels-easy/tree/main/example).
Get full example project [here](./example).

**Server side**
```python
Expand All @@ -64,7 +66,7 @@ class NewConsumer(AsyncWebsocketConsumer):
# output:
# message from client {'text': 'hello'}

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

```

Expand Down Expand Up @@ -140,8 +142,8 @@ def on_message(self, data):

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

Expand Down
2 changes: 1 addition & 1 deletion example/channels_app/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ async def disconnect(self, close_code):

async def on_message(self, data):
print("message from client", data)
await self.emit("message", "room1", {"message": "hello from server"})
await self.emit("message", {"message": "hello from server"}, "room1")
3 changes: 2 additions & 1 deletion mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ nav:
- Home: index.md
- API Reference: apis.md

theme: readthedocs
theme:
name: "material"

plugins:
- search
Expand Down
46 changes: 45 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "channels-easy"
version = "0.2.3"
version = "0.3.0"
description = "A thin wrapper around channels consumer to make things EASY"
authors = ["Naman Tamrakar <[email protected]>"]
license = "MIT"
Expand All @@ -26,6 +26,7 @@ isort = "^5.10.1"
flake8 = "^4.0.1"
mkdocs = "^1.2.3"
mkdocstrings = "^0.17.0"
mkdocs-material = "^8.1.6"

[build-system]
requires = ["poetry-core>=1.0.0"]
Expand Down
8 changes: 4 additions & 4 deletions tests/test_channels_easy.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@


def test_version():
assert __version__ == "0.2.3"
assert __version__ == "0.3.0"


@pytest.mark.django_db
Expand All @@ -24,7 +24,7 @@ async def connect(self):

async def on_message(self, data):
results["received"] = data
await self.emit("message", room, data)
await self.emit("message", data, room)

async def disconnect(self, code):
await self.leave(room)
Expand Down Expand Up @@ -62,7 +62,7 @@ async def connect(self):

async def on_message(self, data):
results["received"] = data
await self.emit("message", room, data)
await self.emit("message", data, room)

async def disconnect(self, code):
await self.leave(room)
Expand Down Expand Up @@ -99,7 +99,7 @@ async def connect(self):

async def on_message(self, data):
results["received"] = data
await self.close_with_error("some error!")
await self.emit_error("some error!", close=True)

async def disconnect(self, code):
results["disconnected"] = True
Expand Down

0 comments on commit e62132a

Please sign in to comment.