Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions app/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,21 @@
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""

import os

import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack

from app.routing import application as application_routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings')

application = get_asgi_application()
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
application_routing
)
),
})
45 changes: 45 additions & 0 deletions app/consumers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import json
from channels.generic.websocket import AsyncWebsocketConsumer

class MessageConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = "messages"
self.room_group_name = "chat_%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
)

# 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': 'chat_message',
'message': message
}
)

# Receive message from room group
async def chat_message(self, event):
message = event['message']

# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message
}))
17 changes: 17 additions & 0 deletions app/routing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.urls import path
from your_app.consumers import MessageConsumer
from django.core.asgi import get_asgi_application

from app.urls import websocket_urlpatterns, urlpatterns


application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
),
})
9 changes: 7 additions & 2 deletions app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,12 @@
'rest_framework',
"corsheaders",
'cms',
'messaging'
'messaging',
'channels',
]



REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
Expand Down Expand Up @@ -78,6 +81,8 @@

ROOT_URLCONF = 'app.urls'



TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
Expand All @@ -94,9 +99,9 @@
},
]

ASGI_APPLICATION = 'app.asgi.application'
WSGI_APPLICATION = 'app.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

Expand Down
5 changes: 5 additions & 0 deletions app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,8 @@
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

websocket_urlpatterns = [
# re_path(r'ws/test/', MachineConsumer.as_asgi()),
# re_path(r'ws/room/(?P<room_id>\w+)/$', MachineConsumer.as_asgi()),
]
36 changes: 18 additions & 18 deletions messaging/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from rest_framework import status
from .models import Conversation, Message
from .serializers import ConversationSerializer, MessageSerializer
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync

class ConversationViewSet(viewsets.ModelViewSet):
queryset = Conversation.objects.all()
Expand Down Expand Up @@ -34,21 +36,19 @@ class MessageViewSet(viewsets.ModelViewSet):
queryset = Message.objects.all()
serializer_class = MessageSerializer

# def create(self, request, *args, **kwargs):
# serializer = self.get_serializer(data=request.data)
# serializer.is_valid(raise_exception=True)
# self.perform_create(serializer)
# return Response(serializer.data, status=status.HTTP_201_CREATED)

# def update(self, request, *args, **kwargs):
# partial = kwargs.pop('partial', False)
# instance = self.get_object()
# serializer = self.get_serializer(instance, data=request.data, partial=partial)
# serializer.is_valid(raise_exception=True)
# self.perform_update(serializer)
# return Response(serializer.data)

# def destroy(self, request, *args, **kwargs):
# instance = self.get_object()
# self.perform_destroy(instance)
# return Response(status=status.HTTP_204_NO_CONTENT)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)

# Send WebSocket notification
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
"chat_messages", # This should match the group name in the consumer
{
"type": "chat_message",
"message": serializer.data, # Send the serialized message data
},
)

return Response(serializer.data, status=status.HTTP_201_CREATED)
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ sqlparse==0.5.0
typing_extensions==4.12.1
zipp==3.19.2
django-csvimport==3.2
channels==4.1.0