This blog post outlined how to get the user from the session key: http://scottbarnham.com/blog/2008/12/04/get-user-from-session-key-in-django/
Unfortunately, it assumes DB-backed session and auth backends. This isn't required, so this snippet provides a backend-agnostic way to do the same thing.
>>> skey = 'ea0ed02d35d43aeaf20b3ef516f51396'
>>> user_from_session_key(skey)
<User: jeremyd>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | def user_from_session_key(session_key):
from django.conf import settings
from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, load_backend
from django.contrib.auth.models import AnonymousUser
session_engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
session_wrapper = session_engine.SessionStore(session_key)
user_id = session_wrapper.get(SESSION_KEY)
auth_backend = load_backend(session_wrapper.get(BACKEND_SESSION_KEY))
if user_id and auth_backend:
return auth_backend.get_user(user_id)
else:
return AnonymousUser()
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
This snippet didn't work for me (under Django 1.2). Here's a modified version that seems to do the trick:
#
Please login first before commenting.