Django Channels:从外部Consumer类发送消息



我是Python和Django的新手,
目前,我需要使用通道设置WebSocket服务器。

使用Django channel从外部的Consumer类发送消息

setting.py

ASGI_APPLICATION = 'myapp.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels.layers.InMemoryChannelLayer',
},
}

下面是代码Consumer

import json
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
class ZzConsumer(WebsocketConsumer):
def connect(self):
self.room_group_name = 'test'
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def disconnect(self, code):
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
print("DISCONNECED CODE: ",code)
def receive(self, text_data=None, bytes_data=None):
print(" MESSAGE RECEIVED")
data = json.loads(text_data)
message = data['message']
async_to_sync(self.channel_layer.group_send)(
self.room_group_name, 
{
"type": 'chat_message',
"message": message
}
)
def chat_message(self, event):
print("EVENT TRIGERED")
# Receive message from room group
message = event['message']
# Send message to WebSocket
self.send(text_data=json.dumps({
'type': 'chat',
'message': message
}))

和消费者之外:

channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
'test',
{
'type': 'chat_message',
'message': "event_trigered_from_views"
}
) 

期望的逻辑是我可以从Consumer类上的receive中的group_send接收数据。这样我可以发送消息给客户端。

然而,它不是。

这里有人知道我错过了什么吗?非常感谢任何帮助。
谢谢!

更新:
routing.py

from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/socket-server/', consumers.ZzConsumer.as_asgi())
]

我认为你在chat_message方法中缺少type参数。它应该与group_send中的类型匹配。例如:

def chat_message(self, event, type='chat_message'):
print("EVENT TRIGERED")

匹配:

async_to_sync(channel_layer.group_send)(
'test',
{
'type': 'chat_message',
'message': "event_trigered_from_views"
}
) 

最新更新