与小组实时交谈

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字母替换无效   java Spring Roo JPA MS SQL Server无法打开JPA EntityManager组织。冬眠例外GenericJDBCException:无法打开连接   在scala中使用JavaWS对大型数据文件进行java流式处理   Java编译器是否将字节和短字符识别为文本?   java无法查找符号错误,空指针   mongodb在Java中重用数据库连接   java将多个StringArray从字符串文件获取到活动中   java是一个变量,它只保存最后一次鼠标单击的坐标   c#尺寸有限;添加、删除和洗牌   java如何在Android中显示来自资产文件夹的文本文件中的文本   Android应用程序中的java Tensorflow Lite自定义对象检测模型错误   java如何在foreachloop中使用scanner将来自命令行的输入存储到数组中   java如何定义一个好的存储库接口   Android中的java解析动态json对象