Created
July 10, 2017 12:31
-
-
Save arujit/de021723fa14d4687532434c0dd73cd1 to your computer and use it in GitHub Desktop.
cherrys support for json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cherrypy | |
import datetime | |
from cherrys import RedisSession | |
import json | |
class RedisJsonSession(RedisSession): | |
def _load(self): | |
try: | |
return json.loads(self.cache.get(self.id)) | |
except TypeError: | |
return None | |
except ValueError: | |
return None | |
def _save(self, expiration_time): | |
print self._data | |
#self._data["time"] = unicode(expiration_time) | |
json_data = json.dumps((self._data,{"time":unicode(expiration_time)})) | |
result = self.cache.setex(self.id, json_data, self.timeout * 60) | |
if not result: | |
raise AssertionError("Session data for id %r not set." % self.id) | |
def load(self): | |
# Copy stored session data into this session instance. | |
data = self._load() | |
""" | |
print data[1] | |
print data[0] | |
print self.now() | |
print "***************" | |
""" | |
print data | |
#print type(data) | |
#print data[1]["time"][:19] | |
# data is either None or a tuple (session_data, expiration_time) | |
if data is None or datetime.datetime.strptime(data[1]["time"][:19], "%Y-%m-%d %H:%M:%S") < self.now(): | |
if self.debug: | |
cherrypy.log('Expired session, flushing data', 'TOOLS.SESSIONS') | |
self._data = {} | |
else: | |
if self.debug: | |
cherrypy.log('Data loaded for session %r.' % self.id, | |
'TOOLS.SESSIONS') | |
self._data = data[0] | |
self.loaded = True | |
# Stick the clean_thread in the class, not the instance. | |
# The instances are created and destroyed per-request. | |
cls = self.__class__ | |
if self.clean_freq and not cls.clean_thread: | |
# clean_up is in instancemethod and not a classmethod, | |
# so that tool config can be accessed inside the method. | |
t = cherrypy.process.plugins.Monitor( | |
cherrypy.engine, self.clean_up, self.clean_freq * 60, | |
name='Session cleanup') | |
t.subscribe() | |
cls.clean_thread = t | |
t.start() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment