I would love to use redis (django-redis-cache) at my website as SESSION_ENGINE and site cache. The problem is that I only want to allow one session per user at a time. Previously It did that using the following signal:
@receiver(user_logged_in)
def remove_other_sessions(sender, user, request, **kwargs):
# remove other sessions
old_sessions = Session.objects.filter(usersession__user=user)
if request.session.session_key:
old_sessions = old_sessions.exclude(session_key=request.session.session_key)
old_sessions.delete()
# save current session
request.session.save()
# create a link from the user to the current session (for later removal)
UserSession.objects.get_or_create(
user=user,
session=Session.objects.get(pk=request.session.session_key)
)
and the following model:
class UserSession(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
session = models.OneToOneField(Session, on_delete=models.CASCADE)
which was working pretty well so far. Sadly I made the experience that when using a scaleable Database like Galera wired HTTP error 400 are getting returned by my site as the session key seems to be unreachable on high I/O, that's why I wanted to switch over to Redis and have it all located at the In-Memory Database Redis provides. But how I can fetch session keys to check if there is already a session existing for a user and if so delete the session like shown above ...
Thanks in advance
question from:
https://stackoverflow.com/questions/65648262/django-redis-session-engine-only-allow-one-session-at-a-time 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…