แรงบันดาลใจจาก channels NEJMA ช่วยให้คุณจัดการและส่งข้อความไปยังกลุ่มช่อง
สิ่งที่คุณสามารถสร้างด้วย nejma :
ดูตัวอย่างนี้ nejma-chat แอปพลิเคชันแชทง่าย ๆ ที่สร้างขึ้นโดยใช้ nejma และ starlette
$ pip install nejma นี่คือตัวอย่างของการใช้ nejma กับ WebSockets
ช่องนำเข้าช่องแรกและ channel_layer จาก nejma
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 เพียงแค่นำเข้า WebSocketendpoint จาก NEJMA
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 ) คลาส ChannelLayer ที่จัดทำโดย nejma เปิดเผยวิธีการต่อไปนี้:
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 ()