Added websocket endpoint for student statuses

This commit is contained in:
Keannu Christian Bernasol 2023-07-01 15:47:28 +08:00
parent fcd941a80f
commit 4b20812021
5 changed files with 74 additions and 2 deletions

View file

@ -0,0 +1,49 @@
# consumers.py
import json
from .models import StudentStatus
from .serializers import StudentStatusSerializer
from djangochannelsrestframework.generics import GenericAsyncAPIConsumer
from djangochannelsrestframework.decorators import action
from djangochannelsrestframework.observer import model_observer, observer
from channels.db import database_sync_to_async
import asyncio
from djangochannelsrestframework.mixins import (
ListModelMixin,
RetrieveModelMixin,
)
class StudentStatusConsumer(
ListModelMixin,
RetrieveModelMixin,
GenericAsyncAPIConsumer,
):
queryset = StudentStatus.objects.all()
serializer_class = StudentStatusSerializer
async def websocket_connect(self, message):
# This method is called when the websocket is handshaking as part of the connection process.
await self.accept()
self.send_updates_task = asyncio.create_task(self.send_updates())
async def websocket_disconnect(self, message):
# This method is called when the WebSocket closes for any reason.
# Here we want to cancel our periodic task that sends updates
self.send_updates_task.cancel()
@database_sync_to_async
def get_student_statuses(self):
queryset = self.get_queryset()
return StudentStatusSerializer(queryset, many=True).data
async def send_updates(self):
while True:
try:
data = await self.get_student_statuses()
print(f"Sending update: {data}") # existing debug statement
await self.send(text_data=json.dumps(data))
await asyncio.sleep(0.5)
except Exception as e:
print(f"Exception in send_updates: {e}")
break # Break the loop on error

View file

@ -0,0 +1,7 @@
# routing.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r"active", consumers.StudentStatusConsumer.as_asgi()),
]

View file

@ -3,5 +3,5 @@ from .views import StudentStatusAPIView, ActiveStudentStatusListAPIView
urlpatterns = [
path('self/', StudentStatusAPIView.as_view()),
path('active_list/', ActiveStudentStatusListAPIView.as_view()),
path('list/', ActiveStudentStatusListAPIView.as_view()),
]