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 AsyncWebsocketConsumerimport jsonclass MyConsumer(AsyncWebsocketConsumer):async def connect(self):self.room_group_name = 'kafka'# Join room groupawait self.channel_layer.group_add(self.room_group_name,self.channel_name)await self.accept()async def disconnect(self, close_code):# Leave room groupawait self.channel_layer.group_discard(self.room_group_name,self.channel_name)# Receive message from WebSocketasync def receive(self, text_data):text_data_json = json.loads(text_data)message = text_data_json['message']# Send message to room groupawait self.channel_layer.group_send(self.room_group_name,{'type': 'kafka_message','message': message})# Receive message from room groupasync def kafka_message(self, event):message = event['message']print('HERE')# Send message to WebSocketawait self.send(text_data=json.dumps({'message': message}))views.pyfrom channels.layers import get_channel_layerfrom asgiref.sync import async_to_sync, sync_to_asyncfrom django.contrib.auth.decorators import login_requiredfrom django.template import loaderfrom .models import artifactInfofrom django.shortcuts import renderfrom django.http import HttpResponse, HttpResponseNotFound, JsonResponseimport os, mimetypes, jsonfrom .logic import send_messageimport logginglogger = 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/36145d13-8828-4dc7-9d4b-4d812d2ad990n%40googlegroups.com.
No comments:
Post a Comment