实时与群体交流
项目描述
⭐ Nejma ⭐
Nejma ⭐ 允许您管理多个实时连接,并向组或用户发送消息,多标签...
查看这个示例 nejma-chat,这是一个使用 nejma 和 starlette 构建的简单聊天应用程序。
安装
$ 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
要使用 nejma 与 starlette,只需从 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 查看哈希值)
      
    
    
       关闭
    
      
        
    
    
  
nejma-0.1.0.tar.gz 的哈希值
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | 21700901af1eac11ff04854c3cefb8ef1f7d6abd831c89347a1a326bb1deac9b | |
| MD5 | 70927e1e378257b68f3d242a0ad4bdd5 | |
| BLAKE2b-256 | bf85c0a72b6c944b6349968575dd0fdcd602047ca105f171872156a4068febae | 
    
       关闭
    
      
        
    
    
  
nejma-0.1.0-py3-none-any.whl 的哈希值
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | 4553ad7fd79282325ba5f0ccc8ac980809dc32bbea420a7c1a37ef0c34161c9e | |
| MD5 | aa7e23f8cbd53ae3cb4daf53f8e72fce | |
| BLAKE2b-256 | 4ca5044bdc4d0fe562ef76c915c4d745b8913a88348847702c86a8a43bbeabe0 |