Sunday, April 2, 2023

I am struggling with calling consumer.py function from views to consumer in django here ismy code. Please help me. I am calling Asyncwebsocketconsumer

from channels.generic.websocket import AsyncWebsocketConsumer
import json

class MyConsumer(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']
        print('HERE')
        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message
        }))



views.py

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync, sync_to_async
from django.contrib.auth.decorators import login_required
from django.template import loader
from .models import artifactInfo
from django.shortcuts import render
from django.http import HttpResponse,  HttpResponseNotFound, JsonResponse
import os, mimetypes, json
from .logic import send_message
import logging
logger = logging.getLogger(__name__)

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


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5cf7970c-1823-414e-bf23-f8805626194bn%40googlegroups.com.

No comments:

Post a Comment