Krishna Sunuwar
Krishna Sunuwar

Reputation: 2947

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

I want to send some message from Django view to django channels consumer. 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:

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:

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. However, I can send message from/within consumer i.e. KafkaConsumer.receive in channels consumer.

Upvotes: 5

Views: 2638

Answers (1)

Krishna Sunuwar
Krishna Sunuwar

Reputation: 2947

Pretty much silly mistake on async_to_sync. Actually async_to_sync should wrap only channel_layer.group_send instead of whole i.e. 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>')

Upvotes: 6

Related Questions