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