websocket Django Channels group send不向组发送任何数据

xzv2uavs  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(136)

我的WebSocket工作正常,但不向组发送任何数据

# settings.py

INSTALLED_APPS = [
    'daphne',
    # admin interface
    'jet',
    # django apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 3rd party
    'django_otp',
    'django_otp.plugins.otp_totp',
    'drf_spectacular',
    'rest_framework',
    'multiselectfield',
    'django_celery_results',
    'django_celery_beat',
    'channels',
    # my apps
    "ads",
    "authentication",
]

# WSGI_APPLICATION = 'gozle_ads.wsgi.application'
ASGI_APPLICATION = 'gozle_ads.asgi.application'

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

# consumers.py

import json

from asgiref.sync import async_to_sync

from channels.generic.websocket import WebsocketConsumer

class BannerConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()
        
        self.room_name = "banner_changer"
        self.room_group_name = "banner_changer_group"

        async_to_sync(self.channel_layer.group_add)(
            self.room_name, self.room_group_name
        )
        self.send(json.dumps({"messgae": "Connected to the banner websocket"}))

    def receive(self, text_data=None):
        async_to_sync(self.channel_layer.group_send)(
            "banner_changer_group",
            {
                "type": "banner_ads_socket",
                "value": f"{text_data}"
            }
        )
    
    def disconnect(self, code):
        print("DISCONNECTED")

    def banner_ads_socket(self, event):
        print("BANNER ADS")
        print(event)

# asgi.py

import os

from django.core.asgi import get_asgi_application
from django.urls import re_path

from channels.routing import ProtocolTypeRouter, URLRouter

from ads.consumers import BannerConsumer

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gozle_ads.settings')

ws_patterns = [
    re_path(r"ws/banner/", BannerConsumer.as_asgi())
]

application = ProtocolTypeRouter({
        "http": get_asgi_application(),
        "websocket": URLRouter(ws_patterns),
})

字符串
当我向receive方法发送数据时,什么都没有发生,方法banner_ads_socket不工作。它不会引发任何错误。首先,我将消费者添加到我的组,然后向组发送数据。我从视频中复制了它。在中,这段代码可以工作,但我的代码不行。我该怎么办?

4ngedf3f

4ngedf3f1#

这可能是由于self.room_nameself.room_group_name如何在connect中分配,并在group_addgroup_send中引用。
您应该使用room_group_name来添加组和发送消息,即

async_to_sync(self.channel_layer.group_add)(self.room_group_name, self.channel_name)

字符串

相关问题