Skip to content

Instantly share code, notes, and snippets.

@glarrain
Created October 30, 2012 19:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save glarrain/3982485 to your computer and use it in GitHub Desktop.
Save glarrain/3982485 to your computer and use it in GitHub Desktop.
Decode session data, no matter what hashes say. It helps in some cases where the Session.get_decoded method returns an empty dictionary because it is "suspicious" of user-data tampering. Based on source code from the Django project.
import base64
import pickle
from django.contrib.sessions.models import Session
from django.utils.encoding import force_unicode
def decode_session_data(session_key):
"""Decode the data in a session object stored under ``session_key``.
:param session_key: e.g. ``'1180b5ed42c2a3a5f217e35b755865da'``
:return: decoded session data
:rtype: :class:`dict`
"""
session_obj = Session.objects.get(pk=session_key)
session_data = force_unicode(session_obj.session_data)
encoded_data = base64.decodestring(session_data)
hash, pickled = encoded_data.split(':', 1)
return pickle.loads(pickled)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment