django Channels 即时通讯应用
对于channels配置官网上有详细的示范案列直接拉下来用即可
from channels.generic.websocket import AsyncWebsocketConsumer
import json
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
# Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
# Receive message from WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
# Receive message from room group
async def chat_message(self, event):
message = event['message']
# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message
}))
现在的代码就可以实现双方连接到频道内的通讯功能
例如要实现消息的通知
@receiver(post_save, sender=chat)
def send_chat(sender, instance, **kwargs):
notifications = instance.receiver.received_chat.filter(read_status=0)
channel_layer = get_channel_layer() # 调用channels
count = notifications.count() # 例如通知的个数
#我们可以监听数据库的模型的状态来给评到内的所有用户发送一个通知
async_to_sync(channel_layer.group_send)('chat_%s' % instance.receiver.id,
{'type': 'notificate.message', 'count': count})
# chat_%s xxxxxxxx 表示self.room_group_name 房间号
# 然后就是消息的保存mysql来做存储的
async def receive(self, text_data): # 在接收消息的时候可以做一些消息的存储
if text_data_json['chat_type'] in ['0']:
# 用处理数据调用channels 中的database_sync_to_async 数据库处理方式来处理
database_sync_to_async(self.save_message(text_data_json))