perf: 在线用户添加是否活跃的属性

pull/12069/head
feng 2023-11-08 10:26:08 +08:00 committed by Bryan
parent 5e54792d94
commit 7746491e19
2 changed files with 19 additions and 8 deletions

View File

@ -12,6 +12,7 @@ from django.utils.translation import gettext, gettext_lazy as _
from common.db.encoder import ModelJSONFieldEncoder
from common.utils import lazyproperty, i18n_trans
from notifications.ws import WS_SESSION_KEY
from ops.models import JobExecution
from orgs.mixins.models import OrgModelMixin, Organization
from orgs.utils import current_org
@ -275,6 +276,10 @@ class UserSession(models.Model):
def backend_display(self):
return gettext(self.backend)
@property
def is_active(self):
return caches.sismember(WS_SESSION_KEY, self.key)
@property
def date_expired(self):
session_store_cls = import_module(settings.SESSION_ENGINE).SessionStore

View File

@ -1,23 +1,27 @@
import threading
import json
from channels.generic.websocket import JsonWebsocketConsumer
from common.utils import get_logger
from channels.generic.websocket import JsonWebsocketConsumer
from django.core.cache import caches
from common.db.utils import safe_db_connection
from .site_msg import SiteMessageUtil
from common.utils import get_logger
from .signal_handlers import new_site_msg_chan
from .site_msg import SiteMessageUtil
logger = get_logger(__name__)
WS_SESSION_KEY = 'ws_session_key'
class SiteMsgWebsocket(JsonWebsocketConsumer):
refresh_every_seconds = 10
sub = None
refresh_every_seconds = 10
def connect(self):
user = self.scope["user"]
if user.is_authenticated:
self.accept()
session = self.scope['session']
caches.sadd(WS_SESSION_KEY, session.session_key)
self.sub = self.watch_recv_new_site_msg()
else:
self.close()
@ -58,6 +62,8 @@ class SiteMsgWebsocket(JsonWebsocketConsumer):
return new_site_msg_chan.subscribe(handle_new_site_msg_recv)
def disconnect(self, code):
if self.sub:
self.sub.unsubscribe()
if not self.sub:
return
self.sub.unsubscribe()
session = self.scope['session']
caches.srem(WS_SESSION_KEY, session.session_key)