与小组实时交谈
nejma的Python项目详细描述
奈杰玛
nejma允许您管理多个实时连接并向组或用户发送消息多个选项卡…
看看这个例子nejma-chat
,一个使用nejma
和starlette
构建的简单聊天应用程序。
安装
$ pip install nejma
开始
下面是一个对websockets使用nejma
的示例。
首先从NEJMA导入通道和通道层
fromnejmaimportChannel,channel_layer
在“连接”上创建频道
asyncdefon_connect(self,websocket,**kwargs):awaitsuper().on_connect(websocket,**kwargs)self.channel=Channel(send=websocket.send)
添加组、频道或发送消息
asyncdefon_receive(self,websocket,data):# Adds a channel to a giving groupself.channel_layer.add(group,self.channel)# Removes a channel from a given groupself.channel_layer.remove(group,self.channel)# Removes a channel from all the groupsself.channel_layer.remove_channel(self.channel)# Reset all the groupsself.channel_layer.flush()awaitself.channel_layer.group_send(group,"Welcome !")
最后,在连接关闭后卸下通道
asyncdefon_disconnect(self,websocket,close_code):self.channel_layer.remove_channel(self.channel)
星体
要将nejma
与starlette
一起使用,只需从nejma导入websocketendpoint
fromchannels.ext.starletteimportWebSocketEndpoint@app.websocket_route("/ws")classChat(WebSocketEndpoint):encoding="json"asyncdefon_receive(self,websocket,data):room_id=data['room_id']message=data['message']username=data['username']ifmessage.strip():group=f"group_{room_id}"self.channel_layer.add(group,self.channel)payload={"username":username,"message":message,"room_id":room_id}awaitself.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()