nejma
1.0.0
channelsに触発されたNEJMAは、チャネルのグループにメッセージを管理および送信できます
nejmaで構築できるもの:
nejmaとstarletteを使用して構築されたシンプルなチャットアプリケーションであるnejma-chat例をご覧ください。
$ pip install nejmanejma WebSocketsで使用する例は次のとおりです。
NEJMAの最初のインポートチャネルとChannel_Layer
from nejma import Channel , channel_layerConnectにチャネルを作成します
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からWebSocketEndPointをインポートするだけです
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 ()