Browse Source

perf: 在线用户根据websocket添加用户是否活跃状态

pull/12069/head
feng 1 year ago committed by Bryan
parent
commit
5ab8ff4fde
  1. 5
      apps/audits/models.py
  2. 2
      apps/audits/serializers.py
  3. 8
      apps/notifications/ws.py

5
apps/audits/models.py

@ -4,7 +4,7 @@ from datetime import timedelta
from importlib import import_module
from django.conf import settings
from django.core.cache import caches
from django.core.cache import caches, cache
from django.db import models
from django.db.models import Q
from django.utils import timezone
@ -278,7 +278,8 @@ class UserSession(models.Model):
@property
def is_active(self):
return caches.sismember(WS_SESSION_KEY, self.key)
redis_client = cache.client.get_client()
return redis_client.sismember(WS_SESSION_KEY, self.key)
@property
def date_expired(self):

2
apps/audits/serializers.py

@ -177,7 +177,7 @@ class UserSessionSerializer(serializers.ModelSerializer):
fields_mini = ['id']
fields_small = fields_mini + [
'type', 'ip', 'city', 'user_agent', 'user', 'is_current_user_session',
'backend', 'backend_display', 'date_created', 'date_expired'
'backend', 'backend_display', 'is_active', 'date_created', 'date_expired'
]
fields = fields_small
extra_kwargs = {

8
apps/notifications/ws.py

@ -1,7 +1,7 @@
import json
from channels.generic.websocket import JsonWebsocketConsumer
from django.core.cache import caches
from django.core.cache import cache
from common.db.utils import safe_db_connection
from common.utils import get_logger
@ -21,7 +21,8 @@ class SiteMsgWebsocket(JsonWebsocketConsumer):
if user.is_authenticated:
self.accept()
session = self.scope['session']
caches.sadd(WS_SESSION_KEY, session.session_key)
redis_client = cache.client.get_client()
redis_client.sadd(WS_SESSION_KEY, session.session_key)
self.sub = self.watch_recv_new_site_msg()
else:
self.close()
@ -66,4 +67,5 @@ class SiteMsgWebsocket(JsonWebsocketConsumer):
return
self.sub.unsubscribe()
session = self.scope['session']
caches.srem(WS_SESSION_KEY, session.session_key)
redis_client = cache.client.get_client()
redis_client.srem(WS_SESSION_KEY, session.session_key)

Loading…
Cancel
Save