python - Django 引导来自 Consumers.py 外部的消息传递

标签 python django-channels

我按照 Django Channels 文档教程创建了一个聊天应用程序。现在我想从另一个应用程序的views.py向consumer.py之外发送消息。但是,每次我触发该函数时,消费者类中的 chat_message 函数都不会触发。 chat_message 函数在消费者范围内正常运行。下面是我使用 websockets 打开聊天页面的浏览器选项卡,然后从不同的浏览器登录的回溯。 chat_message 函数中的“ccc”未打印。对于我在使用消费者之外的 channel 时错过了什么有什么想法吗?

users.views.py中的部分登录功能

...
channel_layer = get_channel_layer()
print("channel_layer: "+ str(channel_layer))
async_to_sync(channel_layer.group_send(
   "chat_hi", {
   "type": "chat.message",
   "message": "from views",
}))
...

回溯

...
WebSocket HANDSHAKING /ws/chat/abc/ [127.0.0.1:56478]
chat_abc
WebSocket CONNECT /ws/chat/abc/ [127.0.0.1:56478]
channel_layer: RedisChannelLayer(hosts=[{'address': ('127.0.0.1', 6379)}])
HTTP POST /accounts/login/ 302 [0.97, 127.0.0.1:54362]
...

聊天.consumers.py

class OnlineFriends(AsyncWebsocketConsumer):
        async def connect(self):
            self.room_name = self.scope['url_route']['kwargs']['room_name']
            self.room_group_name = 'chat_%s' % self.room_name
            print(self.room_group_name)
            await self.channel_layer.group_add(
                self.room_group_name,
                self.channel_name
            )

            await self.accept()

        async def disconnect(self, close_code):
            print("aa")

            await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

        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
                }
            )

        async def chat_message(self, event):
            print("ccc")
            message = event['message']

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

聊天.路由.py

websocket_urlpatterns = [
    re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.OnlineFriends.as_asgi()),
]

asgi.py

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

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

设置.py

ASGI_APPLICATION = "music.asgi.application"

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

最佳答案

您使用的async_to_sync错误。在您的代码中,您立即调用 channel_layer.group_send 。正确的做法如下:

async_to_sync(channel_layer.group_send)(room.channel_name, {
            'type': 'chat_message',
            'data': {'message': 'from views'}
        })

检查最后一个代码片段here

关于python - Django 引导来自 Consumers.py 外部的消息传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68604859/

相关文章:

python - 如何在 RQ python 中通过 id 获取作业?

python - 让 Pip 在 Windows 上使用 MinGW32?

python - 如何将今天的日期添加到 django 模板

python - Django channel websocket.receive 未处理

Django Channels 2.x 还是 Ajax?

python - Django 信号与 channel

python - 如何从列表类别中对 pandas 数据框进行排序?

python - 如何使用opencv轮廓裁剪对象/从图像中获取位置信息

django - 使用 MySQL <> WebSocket 实时更新 Django 应用程序

django - 使用 Apache 引导流量在类生产环境中为 Django channel 提供服务