跳转到主要内容

实时与群体交流

项目描述

⭐ Nejma ⭐

Nejma ⭐ 允许您管理多个实时连接,并向组或用户发送消息,多标签...

查看这个示例 nejma-chat,这是一个使用 nejmastarlette 构建的简单聊天应用程序。

安装

$ pip install nejma

入门

以下是一个使用 nejma 与 websockets 的示例。

首先从 nejma 导入 Channel 和 channel_layer

from nejma import Channel, channel_layer

在连接时创建一个频道

async def on_connect(self, websocket, **kwargs):
    await super().on_connect(websocket, **kwargs)

    self.channel = Channel(send=websocket.send)

添加组、频道或发送消息

    async def on_receive(self, websocket, data):
    	# Adds a channel to a giving group
        self.channel_layer.add(group, self.channel)

        # Removes a channel from a given group
        self.channel_layer.remove(group, self.channel)

        # Removes a channel from all the groups
        self.channel_layer.remove_channel(self.channel)

        # Reset all the groups
        self.channel_layer.flush()

        await self.channel_layer.group_send(group, "Welcome !")

最后,在连接关闭时删除频道

    async def on_disconnect(self, websocket, close_code):
        self.channel_layer.remove_channel(self.channel)

Starlette


要使用 nejmastarlette,只需从 nejma 导入 WebSocketEndpoint

from channels.ext.starlette import WebSocketEndpoint

@app.websocket_route("/ws")
class Chat(WebSocketEndpoint):
    encoding = "json"

    async def on_receive(self, websocket, data):
        room_id = data['room_id']
        message = data['message']
        username = data['username']

        if message.strip():
            group = f"group_{room_id}"

            self.channel_layer.add(group, self.channel)

            payload = {
                "username": username,
                "message": message,
                "room_id": room_id
            }
            await self.channel_layer.group_send(group, payload)

文档

nejma 提供的 ChannelLayer 类公开了以下方法

add(group, channel)

向给定的组添加频道。

	self.channel_layer.add(group, self.channel)

remove(group, channel) 从给定的组中删除频道

self.channel_layer.remove(group, self.channel)

remove_channel(channel) 从所有组中删除频道

self.channel_layer.remove_channel(self.channel)

flush() 重置所有组

self.channel_layer.flush()

项目详情


下载文件

下载适合您平台文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分布

nejma-0.1.0.tar.gz (3.3 kB 查看哈希值)

上传时间 源代码

构建版本

nejma-0.1.0-py3-none-any.whl (5.1 kB 查看哈希值)

上传时间 Python 3

由...