can you provide more details about the specific issues you are facing when 
trying to call this method? Are you getting any error messages, or is the 
function simply not being called? Any additional information you can 
provide will help me better understand your problem.

I am providing you with one of my codes for your preference. Please find 
the attached code in this email.If you have any questions or concerns, 
please do not hesitate to reach out to me.
import json
from channels.generic.websocket import AsyncWebsocketConsumer

class NotificationConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'notification_%s' % self.room_name

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

    async def send_notification(self, event):
        message = json.loads(event['message'])

        # Send message to WebSocket
        await self.send(text_data=json.dumps(message))


views.py

        # order notification inside function ... when receiving order 
    message = "New order received ... .. ect...messages"
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        "notification_to_admin",
        {
            'type': 'send_notification',
            'message': json.dumps(message)
        }
    )

"when using Django Channels, you need to use an ASGI server instead of a 
traditional WSGI 
server to serve your Django application.ASGI (Asynchronous Server Gateway 
Interface) is a standard interface for 
Python web servers to support asynchronous web applications. It allows for 
more efficient handling of long-lived 
connections, such as WebSockets, and enables Django to handle asynchronous 
requests and responses."
asgi.py
import os
import django
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'EcomShoppers.settings')
django.setup()

from channels.auth import AuthMiddleware, AuthMiddlewareStack
from notifications.routing import websocket_urlpatterns
application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AuthMiddlewareStack(
        URLRouter(
            websocket_urlpatterns
        )
    )
})
On Sunday, April 2, 2023 at 7:57:09 PM UTC+5:30 Sneha Vishwakarma wrote:

> 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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/36145d13-8828-4dc7-9d4b-4d812d2ad990n%40googlegroups.com.

Reply via email to