nejma
1.0.0
受channels的启发,NEJMA允许您管理并将消息发送到频道组
您可以使用nejma构建的东西:
看看这个示例nejma-chat ,这是一个使用nejma和starlette构建的简单聊天应用程序。
$ pip install nejma这是将nejma与Websocket一起使用的示例。
nejma的第一个导入频道和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 ):
self . channel_layer . add ( group , self . channel )
await self . channel_layer . group_send ( group , "Welcome !" )Finnaly,连接后卸下通道
async def on_disconnect ( self , websocket , close_code ):
self . channel_layer . remove_channel ( self . channel )要将nejma与starlette一起使用,只需从Nejma导入WebSocketDoint
from nejma . 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, send=None)
将频道添加到一个捐赠组中。
self . channel_layer . add ( group , self . channel , send = websocket . send ) async group_send(group, "Welcome !")
向一组频道发送消息
await self . channel_layer . group_send ( group , "Welcome !" ) 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 ()