Skip to content

Commit

Permalink
JSON support in serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
amol- committed Nov 20, 2015
2 parents a302a64 + 28eae98 commit 7027289
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
18 changes: 12 additions & 6 deletions beaker/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ class Session(dict):
:param cookie_expires: Expiration date for cookie
:param cookie_domain: Domain to use for the cookie.
:param cookie_path: Path to use for the cookie.
:param data_serializer: If ``"json"`` or ``"pickle"`` should be used
to serialize data. By default ``pickle`` is used.
:param secure: Whether or not the cookie should only be sent over SSL.
:param httponly: Whether or not the cookie should only be accessible by
the browser not by JavaScript.
Expand All @@ -104,7 +106,7 @@ class Session(dict):
def __init__(self, request, id=None, invalidate_corrupt=False,
use_cookies=True, type=None, data_dir=None,
key='beaker.session.id', timeout=None, cookie_expires=True,
cookie_domain=None, cookie_path='/', secret=None,
cookie_domain=None, cookie_path='/', data_serializer='pickle', secret=None,
secure=False, namespace_class=None, httponly=False,
encrypt_key=None, validate_key=None, **namespace_args):
if not type:
Expand All @@ -126,6 +128,7 @@ def __init__(self, request, id=None, invalidate_corrupt=False,
self.timeout = timeout
self.use_cookies = use_cookies
self.cookie_expires = cookie_expires
self.data_serializer = data_serializer

# Default cookie domain/path
self._domain = cookie_domain
Expand Down Expand Up @@ -260,10 +263,10 @@ def _encrypt_data(self, session_data=None):
nonce = b64encode(os.urandom(6))[:8]
encrypt_key = crypto.generateCryptoKeys(self.encrypt_key,
self.validate_key + nonce, 1)
data = pickle.dumps(session_data, 2)
data = util.serialize(session_data, self.data_serializer)
return nonce + b64encode(crypto.aesEncrypt(data, encrypt_key))
else:
data = pickle.dumps(session_data, 2)
data = util.serialize(session_data, self.data_serializer)
return b64encode(data)

def _decrypt_data(self, session_data):
Expand All @@ -285,15 +288,15 @@ def _decrypt_data(self, session_data):
else:
raise
try:
return pickle.loads(data)
return util.deserialize(data, self.data_serializer)
except:
if self.invalidate_corrupt:
return None
else:
raise
else:
data = b64decode(session_data)
return pickle.loads(data)
return util.deserialize(data, self.data_serializer)

def _delete_cookie(self):
self.request['set_cookie'] = True
Expand Down Expand Up @@ -480,6 +483,8 @@ class CookieSession(Session):
:param cookie_expires: Expiration date for cookie
:param cookie_domain: Domain to use for the cookie.
:param cookie_path: Path to use for the cookie.
:param data_serializer: If ``"json"`` or ``"pickle"`` should be used
to serialize data. By default ``pickle`` is used.
:param secure: Whether or not the cookie should only be sent over SSL.
:param httponly: Whether or not the cookie should only be accessible by
the browser not by JavaScript.
Expand All @@ -491,7 +496,7 @@ class CookieSession(Session):
def __init__(self, request, key='beaker.session.id', timeout=None,
cookie_expires=True, cookie_domain=None, cookie_path='/',
encrypt_key=None, validate_key=None, secure=False,
httponly=False, **kwargs):
httponly=False, data_serializer='pickle', **kwargs):

if not crypto.has_aes and encrypt_key:
raise InvalidCryptoBackendError("No AES library is installed, can't generate "
Expand All @@ -508,6 +513,7 @@ def __init__(self, request, key='beaker.session.id', timeout=None,
self.httponly = httponly
self._domain = cookie_domain
self._path = cookie_path
self.data_serializer = data_serializer

try:
cookieheader = request['cookie']
Expand Down
21 changes: 18 additions & 3 deletions beaker/util.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Beaker utilities"""
from ._compat import PY2, string_type, unicode_text, NoneType, dictkeyslist, im_class, im_func
from ._compat import PY2, string_type, unicode_text, NoneType, dictkeyslist, im_class, im_func, pickle

try:
import threading as _threading
Expand All @@ -15,7 +15,7 @@
import warnings
import sys
import inspect

import json

from beaker.converters import asbool
from beaker import exceptions
Expand All @@ -24,7 +24,8 @@
DEFAULT_CACHE_KEY_LENGTH = 250

__all__ = ["ThreadLocal", "WeakValuedRegistry", "SyncDict", "encoded_path",
"verify_directory"]
"verify_directory",
"serialize", "deserialize"]


def function_named(fn, name):
Expand Down Expand Up @@ -452,3 +453,17 @@ def func_namespace(func):
return '%s.%s' % (kls.__module__, kls.__name__)
else:
return '%s|%s' % (inspect.getsourcefile(func), func.__name__)


def serialize(data, method):
if method == 'json':
return json.dumps(data).encode('zlib')
else:
return pickle.dumps(data, 2)


def deserialize(data_string, method):
if method == 'json':
return json.loads(data_string.decode('zlib'))
else:
return pickle.loads(data_string)

0 comments on commit 7027289

Please sign in to comment.