How to lookup django session for a particular user?

来源:互联网 发布:高中文言文朗读软件 编辑:程序博客网 时间:2024/06/05 09:49

https://stackoverflow.com/questions/235950/how-to-lookup-django-session-for-a-particular-user






up vote33down vote

This answer is being posted five years after the original question, but this SO thread is one of the top Google results when searching for a solution to this problem (and it's still something that isn't supported out of the box with Django).

I've got an alternate solution for the use case where you're only concerned with logged in user sessions, which uses an additional UserSession model to map users to their sessions, something like this:

from django.conf import settingsfrom django.db import modelsfrom django.contrib.sessions.models import Sessionclass UserSession(models.Model):    user = models.ForeignKey(settings.AUTH_USER_MODEL)    session = models.ForeignKey(Session)  

Then you can simply save a new UserSession instance any time a user logs in:

from django.contrib.auth.signals import user_logged_indef user_logged_in_handler(sender, request, user, **kwargs):    UserSession.objects.get_or_create(user = user, session_id = request.session.session_key)user_logged_in.connect(user_logged_in_handler)

And finally when you'd like to list (and potentially clear) the sessions for a particular user:

from .models import UserSessiondef delete_user_sessions(user):    user_sessions = UserSession.objects.filter(user = user)    for user_session in user_sessions:        user_session.session.delete()

That's the nuts and bolts of it, if you'd like more detail I have a blog post covering it.


阅读全文
0 0
原创粉丝点击