django - 如何从 django View 向消费者(django-channels)发送消息?

标签 django django-channels

我想从 Django View 向 django channel 消费者发送一些消息。我有消费者喜欢:

from channels.generic.websocket import AsyncWebsocketConsumer
import json

class KafkaConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_group_name = 'kafka'

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    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': 'kafka_message',
                'message': message
            }
        )

    # Receive message from room group
    async def kafka_message(self, event):
        message = event['message']

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

而且,我的 Django View 是这样的:
from django.views.generic import TemplateView
from django.http import HttpResponse

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


class LogView(TemplateView):
    template_name = "kafka/index.html"


def testview(request):
    channel_layer = get_channel_layer()

    async_to_sync(channel_layer.group_send(
        'kafka',
        {
            'type': 'kafka.message',
            'message': 'Test message'
        }
    ))
    return HttpResponse('<p>Done</p>')

URL url 是这样的:
from django.urls import path
from .views import LogView, testview

urlpatterns = [
    path(r'', LogView.as_view()),
    path(r'test/', testview),

]

所以,当我这样做时 http://mydevhost/test/ ,消费者收不到消息。但是,我可以从/在消费者内部发送消息,即 KafkaConsumer.receive在 channel 消费者。

最佳答案

async_to_sync 上犯了很多愚蠢的错误.其实async_to_sync应该只包装 channel_layer.group_send而不是整个,即 async_to_sync(channel_layer.group_send) .所以调用看起来像:

async_to_sync(channel_layer.group_send)(
    'kafka',
    {
        'type': 'kafka.message',
        'message': 'Test message'
    }
)

所有带有更正代码的查看代码:
from django.views.generic import TemplateView
from django.http import HttpResponse

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


class LogView(TemplateView):
    template_name = "kafka/index.html"


def testview(request):
    channel_layer = get_channel_layer()

    async_to_sync(channel_layer.group_send)(
        'kafka',
        {
            'type': 'kafka.message',
            'message': 'Test message'
        }
    )
    return HttpResponse('<p>Done</p>')

关于django - 如何从 django View 向消费者(django-channels)发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59943869/

相关文章:

python - 目标 WSGI 脚本无法作为 Python 模块加载

Django多语言网站: how to?

python - 预期“权限”实例,得到...权限实例?

python - Django 链接和 is_secure()

django - Django channel 单元测试的虚假数据

django - 将 Django Channels 部署到 Elastic Beanstalk Python3.4 环境

python - Django ORM : how can i see last executed query on fly

python - Django channel : Alternative of Redis for windows machine?

python - Django Channels 停止使用 self.receive_lock.locked 错误

python - Django channel Redis : Exception inside application: Lock is not acquired