Django channel 实时聊天保存发送的消息

标签 django websocket model channel

所以我有一个 Django 应用程序,我在其中使用 channel 来实现实时聊天。我的消费者看起来像这样:

导入json 从 asgiref.sync 导入 async_to_sync 从channels.generic.websocket导入WebsocketConsumer

class ChatConsumer(WebsocketConsumer):
    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
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        username = self.scope["user"]
        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message,
                'user': username.username
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']
        user=event['user']
        print(user)
        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message,
            'user':user
        }))

所以我正在寻找一种方法来保存发送的消息(因为目前它们在刷新时丢失)。我创建了一个 Messages 模型,其中包含用于消息文本的 CharField。我想如果我在 chat_message 函数中执行此操作,我可以保存新消息:

new_message=Messages(text=message)
new_nessage.save()

我的问题是,每当用户连接到聊天时,如何预加载最后 10 条消息?

最佳答案

因此,为了做到这一点,我最终在“接收”函数中将消息保存到数据库中(因为如果将其保存在 chat_message 函数中,则会为每个事件用户保存 1 次)。然后,为了预加载消息,每次打开 websocket 时我都会使用 AJAX 调用,以便使用 python 函数获取最近 10 条消息,然后我将消息作为 JsonResponse 传回( https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html 向下滚动到 AJAX 请求本文的一部分,并按此顺序查看signup.html、urls.py 和views.py 文件以供引用)。

关于Django channel 实时聊天保存发送的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62477711/

相关文章:

mysql - django.db.utils.OperationalError : (1054, "Unknown column ' commons_smsmessages.sent_date' 在 'field list' ")

websocket - 在新的弹出窗口中接听 Twilio 电话

python - Django 模型的子类无法从父类(super class)访问

php - 为多个表一起设计 Zend 模型?

python - 如何使用自定义 Django 后端?

django - 在 App Engine 上运行夹层

websocket - 访问在云服务器上运行的 substrate 前端失败

symfony - WebSocket 无法与服务器建立连接

python - 不能在 pydantic init 函数中定义变量

Django South - 创建非空外键