Get User from session key in Django

4 December 2008

Error emails contain session key

When you get an error email from your Django app telling you someone got a server error, it’s not always easy to tell which user had a problem. It might help your debugging to know or you might want to contact the user to tell them you have fixed the problem.

Assuming the user is logged in when they get the error, the email will contain the session key for that user’s session. The relevant part of the email looks like:

<WSGIRequest
GET:<QueryDict: {}>,
POST:<QueryDict: {}>,
COOKIES:{ 'sessionid': '8cae76c505f15432b48c8292a7dd0e54'},
...

Finding the user from the session

If the session still exists we can find it, unpickle the data it contains and get the user id. Here’s a short script to do just that:

from django.contrib.sessions.models import Session
from django.contrib.auth.models import User

session_key = '8cae76c505f15432b48c8292a7dd0e54'

session = Session.objects.get(session_key=session_key)
uid = session.get_decoded().get('_auth_user_id')
user = User.objects.get(pk=uid)

print user.username, user.get_full_name(), user.email

There it is. Pass in the session key (sessionid cookie) and get back the user’s name and email address.

Plug: Get your own job board at Fuselagejobs

Filed under: Django — Scott @ 9:43 pm

5 Comments »

  1. Nice idea indeed, but actually it would be even better to have it called automatically when django shows the error page to the user. Not surprisingly this is easy to achieve by overwriting the default 500 error handler view in your urlconf.

    The default says:

    “handler500 = ‘django.views.defaults.server_error’“ in “django.conf.urls.defaults“

    that you have imported anyway, so just write your own and be careful not to enter an endless 500 error loop. :)

    Comment by Viktor — 4 December 2008 @ 11:17 pm

  2. The django-command-extensions project has this as a management command ‘print_user_for_session’:

    http://code.google.com/p/django-command-extensions/

    Comment by Doug Napoleone — 4 December 2008 @ 11:53 pm

  3. This is quite a useful script!
    I was just trying to do sth like this with swfupload. Thanks.

    Comment by omtv — 5 December 2008 @ 2:57 am

  4. Great information, it should be part of the error page and also be included in the error messages send to ADMINS on production sites.

    Comment by Jj — 5 December 2008 @ 8:42 pm

  5. You shouldn’t assume that DB-backed sessions are used, or that the auth session item is “_auth_user_id”.

    I’ve posted a snippet to show a backend-agnostic way to do this:
    http://www.djangosnippets.org/snippets/1276/

    Comment by Jeremy Dunck — 5 January 2009 @ 3:17 pm

RSS feed for comments on this post.

Leave a comment