简体   繁体   English

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

[英]How to send message from django view to consumer (django-channels)?

I want to send some message from Django view to django channels consumer.我想从 Django 视图向 django 频道消费者发送一些消息。 I have consumer like:我有消费者喜欢:

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
        }))

And, my Django view is like:而且,我的 Django 视图是这样的:

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 is like: URL url 是这样的:

from django.urls import path
from .views import LogView, testview

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

]

So, when I do http://mydevhost/test/ , consumer do not receive message.因此,当我执行http://mydevhost/test/ ,消费者不会收到消息。 However, I can send message from/within consumer ie KafkaConsumer.receive in channels consumer.但是,我可以从/在消费者内发送消息,即在渠道消费者中的KafkaConsumer.receive

Pretty much silly mistake on async_to_sync . async_to_sync错误非常愚蠢。 Actually async_to_sync should wrap only channel_layer.group_send instead of whole ie async_to_sync(channel_layer.group_send) .实际上async_to_sync应该只包装channel_layer.group_send而不是整个,即async_to_sync(channel_layer.group_send) So call looks like:所以调用看起来像:

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

All view code with corrected code:所有带有更正代码的查看代码:

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>')

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

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