简体   繁体   English

Django Channels:从消费者类外部发送消息

[英]Django Channels: Send message from outside Consumer Class

I'm new in Python and Django,我是 Python 和 Django 的新手,
Currently, I need to setup a WebSocket server using Channels.目前,我需要使用 Channels 设置 WebSocket 服务器。

I follow the code in this link: Send message using Django Channels from outside Consumer class我遵循此链接中的代码: Send message using Django Channels from outside Consumer class

setting.py设置.py

ASGI_APPLICATION = 'myapp.asgi.application'

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels.layers.InMemoryChannelLayer',
    },
}

Here is the code 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
        }))

And outside the Consumer:在消费者之外:

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

The expected logics is I can received the data from the group_send in the receive on the Consumer class.预期的逻辑是我可以在 Consumer 类的receive中从group_send接收数据。 So that I can send message to client.这样我就可以向客户发送消息。

However, It's not.然而,事实并非如此。

Can anyone here know what's I missing?这里的任何人都可以知道我错过了什么吗? Any help is very appreciated.非常感谢任何帮助。
Thanks!谢谢!

Updated:更新:
routing.py路由.py

from django.urls import re_path
from . import consumers

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

I think you're missing type argument in chat_message method.我认为您在chat_message方法中缺少type参数。 It should match the type in group_send .它应该与group_send中的类型匹配。 Ie: IE:

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

Matches:火柴:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM