【问题标题】:Django Channels after sending message, current tab showing 2 messages(sender + receiver) but other tab does not show anything?发送消息后的 Django 频道,当前选项卡显示 2 条消息(发送者 + 接收者)但其他选项卡不显示任何内容?
【发布时间】:2021-02-13 17:02:21
【问题描述】:

我正在关注这个教程Channels Tutorial Link

我的目标是制作一个简单的 asgi 聊天服务器。但它表现出奇怪的行为。从一个选项卡发送的消息..应在当前选项卡中打印“HI”..并且在同一房间连接的选项卡中也应打印“HI”。但是它在当前选项卡中打印两个“HI”,在同一个房间连接的另一个选项卡中没有显示任何消息。

我的 consumer.py 很简单,只是来自教程文件...

import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import 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']

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))

我的设置文件配置为在 127.0.0.1 接收 redis 连接。我正在使用 docker redis 映像,就像教程所说的那样。

ASGI_APPLICATION = 'mysite.asgi.application'
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

我的 asgi.py 文件...按照教程说的配置-->

# mysite/asgi.py
import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import chat.routing

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

application = ProtocolTypeRouter({
  "http": get_asgi_application(),
  "websocket": AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})

【问题讨论】:

    标签: django websocket django-channels


    【解决方案1】:

    这是最新版本的issue。 我通过重新安装包解决了它:channels == 2.4.0

    然后我更改了文件asgi.py,注释掉了那里的行:"http": get_asgi_application(),

    我还从文件 routing.py 中删除了 as_asgi()

    Here是上一版的教程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      • 2015-07-28
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      相关资源
      最近更新 更多