与小组实时交谈

nejma的Python项目详细描述


奈杰玛

nejma允许您管理多个实时连接并向组或用户发送消息多个选项卡…

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

安装

$ 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)

星体


要将nejmastarlette一起使用,只需从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()

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
不推荐使用java AmazonKinesisClient构造函数   java Quartz作业是否在同一个JVM中以自己的线程运行?   在Java中接收安卓推送通知以进行测试   java是对集合进行排序的最佳方法?   安卓 java。lang.NoSuchMethodError org。阿帕奇。http。客户乌提尔斯。我是杜提尔。encPath   java为什么while循环不以额外的“or”条件结束?   Python能否识别Java中使用BCrypt的哈希密码?   在Cygwin中使用附加Java库的windows   java无法从SQLite检索数据   java使用Swingworker给出不正确的结果   使用多线程服务器向特定客户端发送java消息   java在映射未知的Morphia中查询对象