Pylons & Beaker: JSON Encoded Sessions

2019-08-12 13:32发布

Need to read Pylons session data (just read, not write to) in node.js

Once I decode the base64, I'm left with a string containing a serialized Python object which, is a pain to parse in node.js

How can I get Beaker to serialize to JSON instead? For it is far easier for node.js to handle.

1条回答
唯我独甜
2楼-- · 2019-08-12 13:56

i had to look inside beaker to find what you call "Python serialized strings" are python pickles.

i don't think it would be more than a few lines to change it get it to use json to store the dict.

here is a patch against https://bitbucket.org/bbangert/beaker/src/257f147861c8:

diff -r 257f147861c8 beaker/session.py
--- a/beaker/session.py Mon Apr 18 11:38:53 2011 -0400
+++ b/beaker/session.py Sat Apr 30 14:19:12 2011 -0400
@@ -489,10 +489,10 @@
             nonce = b64encode(os.urandom(40))[:8]
             encrypt_key = crypto.generateCryptoKeys(self.encrypt_key,
                                              self.validate_key + nonce, 1)
-            data = util.pickle.dumps(self.copy(), 2)
+            data = util.json.dumps(self.copy())
             return nonce + b64encode(crypto.aesEncrypt(data, encrypt_key))
         else:
-            data = util.pickle.dumps(self.copy(), 2)
+            data = util.json.dumps(self.copy())
             return b64encode(data)

     def _decrypt_data(self):
@@ -504,10 +504,10 @@
                                              self.validate_key + nonce, 1)
             payload = b64decode(self.cookie[self.key].value[8:])
             data = crypto.aesDecrypt(payload, encrypt_key)
-            return util.pickle.loads(data)
+            return util.json.loads(data)
         else:
             data = b64decode(self.cookie[self.key].value)
-            return util.pickle.loads(data)
+            return util.json.loads(data)

     def save(self, accessed_only=False):
         """Saves the data for this session to persistent storage"""
diff -r 257f147861c8 beaker/util.py
--- a/beaker/util.py    Mon Apr 18 11:38:53 2011 -0400
+++ b/beaker/util.py    Sat Apr 30 14:19:12 2011 -0400
@@ -24,6 +24,11 @@
     import pickle
 else:
     import cPickle as pickle
+
+try:
+    import json
+except ImportError:
+    import simplejson as json

 from beaker.converters import asbool
 from beaker import exceptions
查看更多
登录 后发表回答