Django Channels 未接收到从库引发的事件

问题描述 投票:0回答:1

这是我的消费者阶层。

from channels.generic.websocket import WebsocketConsumer,AsyncWebsocketConsumer
from channels.layers import get_channel_layer
import asyncio
import random

import json
class TradeSession(AsyncWebsocketConsumer):
    async def connect(self):
        print("In Consumer Now")
        self.room_name = "test_consumer"
        self.room_group_name = "test_consumer_group"
        await self.channel_layer.group_add(self.room_name, self.channel_name)
        await self.accept()


    async def disconnect(self, close_code):
        print("Disconnected Now")
        await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
        raise channels.exceptions.StopConsumer()



    async def receive(self, text_data=None, bytes_data=None):
        print("Data Recieverd")
        pass


    async def send_number(self, event):
        print("in Send number Send event",event)
        number = event["price"]
        print("Actuly sending now ",number)
        await self.send(text_data=json.dumps({"price": number}))

以下是我尝试发起活动的 Communicator 自由库。

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
import asyncio


class Communicator:
    def __init__(self):
        pass
    
    def send_data_to_channel_layer(self, data, group_name):
        group_name = "test_consumer_group"
        print("In liberary sending data")
        channel_layer = get_channel_layer()
        print("Sendiong now to group",group_name)
        async_to_sync(channel_layer.send)(group_name, {
            "type": "send.number",
            "price": data['price'],
        })
        # print("Message sent to group")

在日志中我可以看到这一点 - 现在发送到组”,group_name 在此日志之后,我在控制台上看不到任何内容

添加到此

  1. 我的 websocket 工作正常,我也从客户端验证了这一点
  2. 我正在使用 redis-channel 进行通道的内部通信
  3. 这是相同的配置
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("localhost", 6379)],
        },
    },
}

我还验证了 redis 正在本地的同一端口上运行,并且我仅在本地尝试所有这些

我不知道我在这里错过了什么。 非常感谢任何帮助。

python django websocket django-channels
1个回答
0
投票

我得到了答案,我使用了错误的函数名称channel_layer.send 应该是channel_layer.group_send

© www.soinside.com 2019 - 2024. All rights reserved.