Skip to content

Instantly share code, notes, and snippets.

@Ciantic
Created June 16, 2010 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ciantic/441132 to your computer and use it in GitHub Desktop.
Save Ciantic/441132 to your computer and use it in GitHub Desktop.
Django JSON serialized database SessionStore
"""Session table that stores session data as JSON
Works similarily as :mod:`django.contrib.sessions.backends.db`
To use this add to your settings.py::
SESSION_ENGINE = 'djangosessionjson'
"""
from django.utils import simplejson as json
from django.conf import settings
from django.core.exceptions import SuspiciousOperation
from django.utils.hashcompat import md5_constructor
from django.contrib.sessions.backends.db import SessionStore as DBSessionStore
class SessionStore(DBSessionStore):
def encode(self, session_dict):
"Returns the given session dictionary pickled and encoded as a string."
pickled = json.dumps(session_dict)
pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest()
return pickled + pickled_md5
def decode(self, session_data):
pickled, tamper_check = session_data[:-32], session_data[-32:]
if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
raise SuspiciousOperation("User tampered with session cookie.")
try:
return json.loads(pickled)
# Unpickling can cause a variety of exceptions. If something happens,
# just return an empty dictionary (an empty session).
except:
return {}
@Ciantic
Copy link
Author

Ciantic commented Jun 16, 2010

Notice that I have not tested this extensively, only thing that mattered for me is that I can login and interact with Django admin. So beware, I am not sure can JSON serialization contain every datatype that session data may contain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment