Permalink
Browse files

Merge pull request #24 from farvour/master

Allow JSON serializer configuration setting.
  • Loading branch information...
didip committed Mar 20, 2014
2 parents 2792fd7 + 7ef62d0 commit de15d431314a0649899c8aad564f77bb2c7af02f
Showing with 25 additions and 5 deletions.
  1. +17 −3 beaker_extensions/nosql.py
  2. +8 −2 beaker_extensions/redis_.py
View
@@ -1,3 +1,4 @@
+import json
import logging
from beaker.container import NamespaceManager, Container
@@ -24,7 +25,10 @@ def __init__(self, namespace, url=None, data_dir=None, lock_dir=None, expire=Non
elif data_dir:
self.lock_dir = data_dir + "/container_tcd_lock"
if hasattr(self, 'lock_dir'):
- verify_directory(self.lock_dir)
+ verify_directory(self.lock_dir)
+
+ # Specify the serializer to use (pickle or json?)
+ self.serializer = params.pop('serializer', 'pickle')
self._expiretime = int(expire) if expire else None
@@ -50,7 +54,14 @@ def _format_key(self, key):
return self.namespace + '_'
def __getitem__(self, key):
- return pickle.loads(self.db_conn.get(self._format_key(key)))
+ if self.serializer == 'json':
+ payload = self.db_conn.get(self._format_key(key))
+ if isinstance(payload, bytes):
+ return json.loads(payload.decode('utf-8'))
+ else:
+ return json.loads(payload)
+ else:
+ return pickle.loads(self.db_conn.get(self._format_key(key)))
def __contains__(self, key):
return self.db_conn.has_key(self._format_key(key))
@@ -59,7 +70,10 @@ def has_key(self, key):
return key in self
def set_value(self, key, value):
- self.db_conn[self._format_key(key)] = pickle.dumps(value, 2)
+ if self.serializer == 'json':
+ self.db_conn[self._format_key(key)] = json.dumps(value, ensure_ascii=True)
+ else:
+ self.db_conn[self._format_key(key)] = pickle.dumps(value, 2)
def __setitem__(self, key, value):
self.set_value(key, value, self._expiretime)
@@ -1,3 +1,4 @@
+import json
import logging
from beaker.exceptions import InvalidCacheBackendError
@@ -57,10 +58,15 @@ def set_value(self, key, value, expiretime=None):
if (expiretime is None) and (type(value) is tuple):
expiretime = value[1]
+ if self.serializer == 'json':
+ serialized_value = json.dumps(value, ensure_ascii=True)
+ else:
+ serialized_value = pickle.dumps(value, 2)
+
if expiretime:
- self.db_conn.setex(key, expiretime, pickle.dumps(value, 2))
+ self.db_conn.setex(key, expiretime, serialized_value)
else:
- self.db_conn.set(key, pickle.dumps(value, 2))
+ self.db_conn.set(key, serialized_value)
def __delitem__(self, key):
self.db_conn.delete(self._format_key(key))

0 comments on commit de15d43

Please sign in to comment.