(self)
| 7 | |
| 8 | class MyWebSocketConsumer(AsyncWebsocketConsumer): |
| 9 | async def connect(self): |
| 10 | self.room_name = "updates" |
| 11 | |
| 12 | user = self.scope["user"] |
| 13 | if not user.is_authenticated: |
| 14 | await self.close() |
| 15 | return |
| 16 | |
| 17 | try: |
| 18 | await self.accept() |
| 19 | await self.channel_layer.group_add(self.room_name, self.channel_name) |
| 20 | await self.send(text_data=json.dumps({ |
| 21 | 'type': 'connection_established', |
| 22 | 'data': { |
| 23 | 'success': True, |
| 24 | 'message': 'WebSocket connection established successfully' |
| 25 | } |
| 26 | })) |
| 27 | # If the IP lookup already completed before the client connected, |
| 28 | # push the cached result immediately so the Skeleton resolves. |
| 29 | try: |
| 30 | from django.core.cache import cache |
| 31 | from core.api_views import _IP_CACHE_KEY |
| 32 | cached_ip = await sync_to_async(cache.get)(_IP_CACHE_KEY) |
| 33 | if cached_ip: |
| 34 | await self.send(text_data=json.dumps({ |
| 35 | 'data': {'type': 'ip_lookup_complete', **cached_ip} |
| 36 | })) |
| 37 | except Exception as e: |
| 38 | logger.warning(f"Could not push cached IP result on connect: {e}") |
| 39 | except Exception as e: |
| 40 | logger.error(f"Error in WebSocket connect: {str(e)}") |
| 41 | try: |
| 42 | await self.close(code=1011) |
| 43 | except: |
| 44 | pass |
| 45 | |
| 46 | async def disconnect(self, close_code): |
| 47 | try: |
no test coverage detected