我使用 Django 和 Redis 作为会话引擎(也是 Celery,但那是别的东西)。它运行完美,我可以看到速度的提高。
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
我有一个脚本每分钟运行一次,通过某些方法检查活动用户,如果用户在最近一分钟内没有活动,则会话将被删除。这样做是为了满足客户的跟踪需求。
在我切换到 Redis 作为会话引擎之前,该脚本一直运行良好。会话确实从数据库中删除,但没有从 Redis 中删除。我没有使用任何 Django 内置方法,而是使用我自己的函数:
def clean_sessions():
stored_sessions = Session.objects.all()
active_users = active_users(minutes=1)
active_users_ids = [user.id for user in active_users]
for session in stored_sessions:
session_uid = session.get_decoded().get('_auth_user_id')
if not session_uid:
session.delete()
continue
if session_uid not in active_users_ids:
user = User.objects.get(pk=session_uid)
## some code between ##
session.delete()
我的问题是,如何从缓存中删除会话,以便用户实际上注销?
这不是很简单,但我能够解决它。我从 clean_sessions() 文件中导入了它:
from importlib import import_module
from django.conf import settings
然后,在函数内部,我加载了 SessionStore 对象:
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
从那里,删除会话非常容易,方法如下:
def clean_sessions():
stored_sessions = Session.objects.all()
active_users = Request.objects.active_users(seconds=15)
active_users_ids = [user.id for user in active_users]
for session in stored_sessions:
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
s = SessionStore(session_key=session.session_key)
session_uid = session.get_decoded().get('_auth_user_id')
if not session_uid:
s.delete()
continue
if session_uid not in active_users_ids:
## some code ##
s.delete()
从您使用的任何会话引擎加载正确的 SessionStore 非常重要,否则它将无法从两个位置(数据库和缓存)中删除它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)