Django频道-实时更新数据库中的更改屏幕

时间:2018-08-07 07:26:04

标签: django websocket django-channels

consumer.py

import json
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
from .models import Thread, ChatMessage


class ChatConsumer(AsyncConsumer):
    async def websocket_connect(self, event):
        self.other_user = self.scope['url_route']['kwargs']['username']
        self.me = self.scope['user']
        self.thread_obj = await self.get_thread(self.me, self.other_user)

        await self.channel_layer.group_add(
            self.channel_name # this is a default attribute of channels
        )
        await self.send({
            "type": "websocket.accept"
        })

    # when you send something from the front-end, you need to receive it
    async def websocket_receive(self, event):
        front_text = event.get('text', None)
        if front_text is not None:
            loaded_dict_data = json.loads(front_text)
            msg = loaded_dict_data.get('message')
            my_response = {
                'message': msg,
                'username': self.me.username,
            }

            await self.create_chat_message(self.me, msg)

            # broadcasts the message event to be sent
            await self.channel_layer.group_send(
                {
                    "type": "chat_message",
                    "text": json.dumps(my_response)
                }
            )

    async def chat_message(self, event):
        # sends the actual message
        await self.send({
            "type": "websocket.send",
            "text": event['text']

        })

    @database_sync_to_async
    def get_thread(self, user, other_username):
        return Thread.objects.get_or_new(user, other_username)[0]

    @database_sync_to_async
    def create_chat_message(self, me, msg):
        return ChatMessage.objects.create(thread=self.thread_obj, user=me, message=msg )

我做了一个聊天网站进行练习。这与this chat website非常相似。目前,我的代码版本与演示网站完全一样。一个用户发送一条消息,该消息将自动实时实时显示在另一位用户的屏幕上,并将聊天消息保存在Thread对象中。

但是,我希望将新的聊天消息直接保存到DB中时,屏幕自动更新。当前,如果我在数据库中插入新的聊天消息行,则该页面不会自动显示新消息。仅当我刷新页面时,屏幕才会更改。我希望它根据数据库中的更改实时更新屏幕。我该如何实现?

我见过有人说我必须使用网上论坛,但是要确定如何实现它。请帮忙!

++ This is probably something similar to what I want

0 个答案:

没有答案