mirror of
https://github.com/lemeow125/StudE-Backend.git
synced 2024-11-17 06:19:24 +08:00
Improved websocket consumer
This commit is contained in:
parent
63d16eae17
commit
8d5a316d54
2 changed files with 34 additions and 11 deletions
|
@ -1,6 +1,7 @@
|
||||||
import os
|
import os
|
||||||
|
|
||||||
from channels.routing import ProtocolTypeRouter, URLRouter
|
from channels.routing import ProtocolTypeRouter, URLRouter
|
||||||
|
from channels.security.websocket import AllowedHostsOriginValidator
|
||||||
from channels.auth import AuthMiddlewareStack
|
from channels.auth import AuthMiddlewareStack
|
||||||
from django.core.asgi import get_asgi_application
|
from django.core.asgi import get_asgi_application
|
||||||
import api.routing
|
import api.routing
|
||||||
|
@ -13,9 +14,11 @@ django_asgi_app = get_asgi_application()
|
||||||
|
|
||||||
application = ProtocolTypeRouter({
|
application = ProtocolTypeRouter({
|
||||||
"http": django_asgi_app,
|
"http": django_asgi_app,
|
||||||
'websocket': AuthMiddlewareStack(
|
'websocket': AllowedHostsOriginValidator(
|
||||||
URLRouter(
|
AuthMiddlewareStack(
|
||||||
[re_path(r'ws/', URLRouter(api.routing.websocket_urlpatterns))]
|
URLRouter(
|
||||||
)
|
[re_path(r'ws/', URLRouter(api.routing.websocket_urlpatterns))]
|
||||||
),
|
)
|
||||||
|
),
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|
|
@ -12,6 +12,12 @@ from djangochannelsrestframework.mixins import (
|
||||||
RetrieveModelMixin,
|
RetrieveModelMixin,
|
||||||
)
|
)
|
||||||
from djangochannelsrestframework.permissions import IsAuthenticated
|
from djangochannelsrestframework.permissions import IsAuthenticated
|
||||||
|
from channels.layers import get_channel_layer
|
||||||
|
from asgiref.sync import async_to_sync
|
||||||
|
from django.contrib.gis.measure import Distance
|
||||||
|
from django.contrib.gis.geos import fromstr
|
||||||
|
from .models import StudentStatus
|
||||||
|
from accounts.models import CustomUser
|
||||||
|
|
||||||
|
|
||||||
class StudentStatusConsumer(
|
class StudentStatusConsumer(
|
||||||
|
@ -23,28 +29,42 @@ class StudentStatusConsumer(
|
||||||
queryset = StudentStatus.objects.filter(active=True)
|
queryset = StudentStatus.objects.filter(active=True)
|
||||||
serializer_class = StudentStatusSerializer
|
serializer_class = StudentStatusSerializer
|
||||||
|
|
||||||
|
async def send_status_update(self, event):
|
||||||
|
data = event['data']
|
||||||
|
await self.send(text_data=json.dumps(data))
|
||||||
|
|
||||||
async def websocket_connect(self, message):
|
async def websocket_connect(self, message):
|
||||||
# This method is called when the websocket is handshaking as part of the connection process.
|
await self.channel_layer.group_add('student_status_group', self.channel_name)
|
||||||
await self.accept()
|
await self.accept()
|
||||||
self.send_updates_task = asyncio.create_task(self.send_updates())
|
self.send_updates_task = asyncio.create_task(self.send_updates())
|
||||||
|
|
||||||
async def websocket_disconnect(self, message):
|
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
|
await self.channel_layer.group_discard('student_status_group', self.channel_name)
|
||||||
self.send_updates_task.cancel()
|
self.send_updates_task.cancel()
|
||||||
|
|
||||||
@database_sync_to_async
|
@database_sync_to_async
|
||||||
def get_student_statuses(self):
|
def get_student_statuses(self):
|
||||||
queryset = self.get_queryset()
|
queryset = self.get_queryset()
|
||||||
|
user = self.scope['user']
|
||||||
return StudentStatusSerializer(queryset, many=True).data
|
return StudentStatusSerializer(queryset, many=True).data
|
||||||
|
|
||||||
async def send_updates(self):
|
async def send_updates(self):
|
||||||
|
channel_layer = get_channel_layer()
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
|
print('attempting to get')
|
||||||
data = await self.get_student_statuses()
|
data = await self.get_student_statuses()
|
||||||
# print(f"Sending update: {data}") Debug
|
print(f"Sending update: {data}")
|
||||||
await self.send(text_data=json.dumps(data))
|
await channel_layer.group_send(
|
||||||
await asyncio.sleep(5)
|
'student_status_group',
|
||||||
|
{
|
||||||
|
'type': 'send_status_update',
|
||||||
|
'data': data,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
await asyncio.sleep(3)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Exception in send_updates: {e}")
|
print(f"Exception in send_updates: {e}")
|
||||||
break # Break the loop on error
|
break # Break the loop on error
|
||||||
|
|
Loading…
Reference in a new issue