Anonymous avatar Anonymous committed 10bf74c

Big clean ups to the sessionfilter. Functions have been given more descriptive names. The sessionFilter can no longer create multiple named sessions based on the confuration settings. This can still be accomplished by manually placing the sessionFilter in _cpFilterList

Comments (0)

Files changed (10)

+2005-08-17:
+    * The session filter has been simplified, the mechanism for creating multiple sessions has been removed. However .. (mikerobi)
+    * The session filter can placed inside a _cpFilterList to provide an alternative to the default session.            (mikerobi)
+    
 2005-08-09:
     * The config section [global] is now distinct from, and the parent of, [/]. (fumanchu)
     * cherrypy.request.path is now parsed and set before onStartResource filter methods are called. (fumanchu)

cherrypy/lib/filter/sessionfilter/__init__.py

     'sessionFilter.storageType' : 'ram',
     'sessionFilter.cookiePrefix': 'CherryPySession',
     'sessionFilter.storagePath': '.sessiondata',
+    'sessionFilter.dbFile': 'sessionData.db',
     'sessionFilter.default.on': True,
     'sessionFilter.cacheTimeout' : 0,
     'sessionFilter.timeMultiple' : 60
 from anydbadaptor import DBMAdaptor
 
 
-_sessionTypes = {
+sessionTypes = {
                   'ram'       : RamAdaptor,
                   'file'      : FileAdaptor,
                   'anydb'     : DBMAdaptor
 try:
     # the user might not have sqlobject instaled
     from sqlobjectadaptor import SQLObjectSession
-    _sessionTypes['sqlobject'] = SQLObjectSession
+    sessionTypes['sqlobject'] = SQLObjectSession
 except ImportError:
     pass
 
     Input filter - get the sessionId (or generate a new one) and load up the session data
     """
 
-    def __init__(self):
+    def __init__(self, sessionName = 'default', sessionPath = '/'):
         """ Initilizes the session filter and creates cherrypy.sessions  """
 
         self.__localData= local()
         
-        self.sessionManagers = {}
         cherrypy.config.update(_sessionDefaults, override = False)
+        self.sessionManager = self.__newSessionManager(sessionName, sessionPath)
+        self.sessionManager.settings = local()
         
-        self.__initSessionManagers()
-
     def __newSessionManager(self, sessionName, sessionPath):
-        """ 
+        """
         Takes the name of a new session and its configuration path.
         Returns a storageAdaptor instance maching the configured storage type.
         If the storage type is not built in, it tries to use sessionFilter.storageAadaptors.
         
         # try to initilize a built in session
         try:
-            try:
-                if sessionName in self.sessionManagers:
-                    raise DuplicateSessionError()
-            except KeyError:
-                pass
-            storageAdaptor = _sessionTypes[storageType]
+            storageAdaptor = sessionTypes[storageType]
         except KeyError:
             # the storageType is not built in
             
         
         return storageAdaptor(sessionName, sessionPath)
     
-    def __initSessionManagers(self):
-        for section, settings in cherrypy.config.configMap.iteritems():
-            for setting, value in settings.iteritems():
-                if not setting.startswith('sessionFilter'):
-                    continue
-
-                keySplit = setting.split('.')
-                if len(keySplit) == 2:
-                    sessionName = 'default'
-                else:
-                    sessionName = keySplit[1]
-                
-                if keySplit[-1] != 'on' or value == False:
-                    continue
-
-                if section == 'global':
-                    path = '/'
-                else:
-                    path = section
-
-                if sessionName not in self.sessionManagers:
-                    sessionManager = self.__newSessionManager(sessionName, path)
-                    # create a new local instance
-                    setattr(sessionManager, 'settings', local())
-
-                    self.sessionManagers[sessionName] = sessionManager
     
-    def __loadConfigData(self, sessionName):
-            sessionManager = self.sessionManagers[sessionName]
-            
+    def __loadConfigData(self, sessionManager):
             settings = {}
             for settingName in _sessionSettingNames:
                 default = cherrypy.config.get('sessionFilter.%s' % settingName)
-                value = cherrypy.config.get('sessionFilter.%s.%s' % (sessionName, settingName), default)
+                value = cherrypy.config.get('sessionFilter.%s.%s' % (sessionManager.name, settingName), default)
                 settings[settingName] = value
                 
                 setattr(sessionManager.settings, settingName, value)
-                
+
     def __loadSessions(self):
+        # look up all of the session keys by cookie
+        sessionManager = self.sessionManager
+        sessionName = sessionManager.name
         
-        # look up all of the session keys by cookie
+        if not cherrypy.config.get('sessionFilter.%s.on' % sessionName, False):
+            return
+
+        self.__loadConfigData(sessionManager)
         
-        for sessionName, sessionManager in self.sessionManagers.iteritems():
-            if not cherrypy.config.get('sessionFilter.%s.on' % sessionName, False):
-                continue
+        cookieName = sessionManager.cookieName
+        
+        try:
+            sessionKey = cherrypy.request.simpleCookie[cookieName].value
+        except KeyError:
+            sessionKey = sessionManager.createSession()
+            self.saveSessionDictKey(sessionKey, sessionManager) 
+            sessionManager.loadSession(sessionKey)
 
-            self.__loadConfigData(sessionName)
-            cookieName = sessionManager.cookieName
-            
-            try:
-                sessionKey = cherrypy.request.simpleCookie[cookieName].value
-            except KeyError:
-                sessionKey = sessionManager.createSession()
-                self.setSessionKey(sessionKey, sessionManager) 
-                sessionManager.loadSession(sessionKey)
+        try:
+            sessionManager.loadSession(sessionKey)
+        except SessionNotFoundError:
+            sessionKey = sessionManager.createSession()
+            self.saveSessionDictKey(sessionKey, sessionManager)  
+            sessionManager.loadSession(sessionKey)
 
-            try:
-                sessionManager.loadSession(sessionKey)
-            except SessionNotFoundError:
-                sessionKey = sessionManager.createSession()
-                self.setSessionKey(sessionKey, sessionManager)  
-                sessionManager.loadSession(sessionKey)
-
-    def setSessionKey(self, sessionKey, sessionManager):
+    def saveSessionDictKey(self, sessionKey, sessionManager):
         """ 
         Sets the session key in a cookie. 
         """
             pass
 
     def __saveSessions(self):
+        try:
+            sessionData = getattr(cherrypy.session, self.sessionManager.name)
         
-        for sessionName, sessionManager in self.sessionManagers.iteritems():
-            if not cherrypy.config.get('sessionFilter.%s.on' % sessionName, False):
-                continue
+            self.sessionManager.commitCache(sessionData.key)
+            self.sessionManager.cleanUpCache()
 
-            sessionData = getattr(cherrypy.session, sessionName)
-            sessionManager.commitCache(sessionData.key)
-            sessionManager.cleanUpCache()
-            
-            sessionManager.cleanUpOldSessions()
-
+            self.sessionManager.cleanUpOldSessions()
+        except AttributeError:
+            return
+        
     def beforeMain(self):
         if (not cherrypy.config.get('staticFilter.on', False)
             and cherrypy.config.get('sessionFilter.on')):

cherrypy/lib/filter/sessionfilter/anydbadaptor.py

         newData = self.getDefaultAttributes()
         return SessionDict(sessionAttributes = newData)
 
-    def getSession(self, sessionKey):
+    def getSessionDict(self, sessionKey):
         try:
             return self.__data[sessionKey]
         except KeyError:
             raise SessionNotFoundError
     
-    def setSession(self, sessionData):
+    def saveSessionDict(self, sessionData):
         self.__data[sessionData.key] = sessionData
 
-    def delSession(self, sessionKey):
+    def deleteSession(self, sessionKey):
         try:
             del self.__data[sessionKey]
         except KeyError:
                 del self.__data[sessionKey]
                 #deleteList.append(sessionKey)
         #for key in deleteList:
-        #    self.delSession(sessionKey)
+        #    self.deleteSession(sessionKey)
 
     def _debugDump(self):
         if not cherrypy.config.get('testMode', False):

cherrypy/lib/filter/sessionfilter/baseadaptor.py

     noCache = True
     
     # these are the  functions that need to rewritten 
-    def delSession(self, sessionKey):
+    def deleteSession(self, sessionKey):
         """ delete a session from storage """
-        raise NotImplementedError('delSession has not been implemented')
+        raise NotImplementedError('deleteSession has not been implemented')
     
-    def getSession(self, sessionKey):
+    def getSessionDict(self, sessionKey):
         """ function to lookup the session """
-        raise NotImplementedError('getSession has not been implemented')
+        raise NotImplementedError('getSessionDict has not been implemented')
     
-    def setSession(self, sessionData):
+    def saveSessionDict(self, sessionData):
         """ function to save sesion data """
-        raise NotImplementedError('setSession has not been implemented')
+        raise NotImplementedError('saveSessionDict has not been implemented')
     
     def _cleanUpOldSessions(self):
         """This function cleans up expired sessions"""
             from cherrypy._cpthreadinglocal import local
 
         # settings dict
-        self.settings = None
+        self.settings = local()
            
     
     # there should never be a reason to modify the remaining functions, they used 
             session.threadCount += 1
         except KeyError:
             # look in the primary storage
-            session = self.getSession(sessionKey)
+            session = self.getSessionDict(sessionKey)
             session.threadCount += 1
             self.__sessionCache[sessionKey] = session
     
     def createSession(self):
         """ returns a session key """
         session = self.newSession()
-        self.setSession(session)
+        self.saveSessionDict(session)
         return session.key
     
     def commitCache(self, sessionKey): 
         try:
             session = self.__sessionCache[sessionKey]
             session.threadCount = 0
-            self.setSession(session)
+            self.saveSessionDict(session)
         
             cacheTimeout = self.settings.cacheTimeout
             

cherrypy/lib/filter/sessionfilter/fileadaptor.py

         return SessionDict(sessionAttributes = newData)
    
     # all session writes are blocked 
-    def getSession(self, sessionKey):
+    def getSessionDict(self, sessionKey):
         if not sessionKey:
             raise SessionNotFoundError
         
         else:
             raise SessionNotFoundError
     
-    def setSession(self, sessionData):
+    def saveSessionDict(self, sessionData):
     
         storagePath = self.settings.storagePath
 
         self.__fileLock.release()
         f.close()
 
-    def delSession(self, sessionKey):
+    def deleteSession(self, sessionKey):
         storagePath = self.settings.storagePath
         fileName = '%s-%s' % (self.name, sessionKey)
         filePath = os.path.join(storagePath, fileName)
             try:
                 prefix, sessionKey = fileName.split('-')
                 if prefix == self.name:
-                    session = self.getSession(sessionKey)
+                    session = self.getSessionDict(sessionKey)
                     if session.expired():
                         os.remove(os.path.join(storagePath, fileName))
             except ValueError:
             try:
                 prefix, sessionKey = fileName.split('-')
                 if prefix == self.name:
-                    dump[sessionKey] = self.getSession(sessionKey)
+                    dump[sessionKey] = self.getSessionDict(sessionKey)
             except ValueError:
                 pass
 

cherrypy/lib/filter/sessionfilter/ramadaptor.py

         newData = self.getDefaultAttributes()
         return SessionDict(sessionAttributes = newData)
         
-    def getSession(self, sessionKey):
+    def getSessionDict(self, sessionKey):
         try:
             return self.__data[sessionKey]
         except KeyError:
             raise SessionNotFoundError
     
-    def setSession(self, sessionData):
+    def saveSessionDict(self, sessionData):
         # since everything in in ram the 
         # session we don't need to update the data
         # unless int is a new session
         if not self.__data.has_key(sessionData.key):
             self.__data[sessionData.key] = sessionData
 
-    def delSession(self, sessionKey):
+    def deleteSession(self, sessionKey):
         try:
             del self.__data[sessionKey]
         except KeyError:
        
         return 
         for key in deleteList:
-            self.delSession(sessionKey)
+            self.deleteSession(sessionKey)
 
     def _debugDump(self):
         if not cherrypy.config.get('testMode', False):

cherrypy/lib/filter/sessionfilter/sessionerrors.py

 
 class SessionBadStorageTypeError(SessionError):
     def __init__(self, storageType):
-        self.storageType = self.storageType
+        self.storageType = storageType
 
     def __str__(self):
         return "Could not find %s storage type." % self.storageType

cherrypy/lib/filter/sessionfilter/sqlobjectadaptor.py

         newSession = self.Session(session_key = self.generateSessionKey())
         return SQLObjectSessionDict(newSession)
         
-    def getSession(self, sessionKey):
+    def getSessionDict(self, sessionKey):
         resultList = list(self.Session.select(self.Session.q.session_key == sessionKey))
         
         if resultList:
         else:
             raise SessionNotFoundError
     
-    def setSession(self, sessionData):
+    def saveSessionDict(self, sessionData):
         # all changes are automatically commited so
         try:
             if self.Session._lazyUpdate:
         except AttributeError:
             pass
         
-    def delSession(self, sessionKey):
+    def deleteSession(self, sessionKey):
         # figure out what to catch when this doesn't work
         Session.delete(Session.q.session_key==sessionKey)
         

cherrypy/test/test_session_filter.py

                     'sessionFilter.cleanUpDelay' : 1,
                     'sessionFilter.timeout' : 1,
                     'testMode' : True
-                    },
-               '/ram':
-                   {'sessionFilter.ram.on': True,
-                    'sessionFilter.ram.storageType': 'ram'},
-               '/file':
-                   {'sessionFilter.file.on': True,
-                    'sessionFilter.file.storageType': 'file'},
-               '/anydb':
-                   {'sessionFilter.anydb.on': True,
-                    'sessionFilter.anydb.storageType': 'anydb'},
-              }
-
+                    }
+}
 
 class TestSite:
     
 
 class SessionFilterTest(helper.CPWebCase):
     
-##    def test_default(self):
-##        self.sessionName = "default"
-##        self.sessionPath = "/"
-##        self.storageType = "ram"
-##        self.persistant  = False
-##        self.doSession()
-##        self.persistant = False
-##        self.doCleanUp()
-##        self.doThreadSafety()
-    
     def test_ram(self):
-        self.sessionName = "ram"
-        self.sessionPath = "/ram"
-        self.storageType = "ram"
+        self.sessionName = "default"
+        cherrypy.config.update({'global' : {'sessionFilter.storageType' : 'ram' }})
+        cherrypy.server.stop()
+        cherrypy.server.start(initOnly = True)
+        self.sessionPath = "/"
         self.persistant  = False
         self.doSession()
         self.persistant = False
         self.doCleanUp()
     
-    def test_file(self):
-        self.sessionName = "file"
+    def _test_file(self):
+        self.sessionName = "default"
         self.sessionPath = "/file"
-        self.storageType = "file"
         self.persistant  = True
         self.doSession()
         self.persistant = False
         self.doCleanUp()
     
-    def test_anydb(self):
-        self.sessionName = "anydb"
+    def _test_anydb(self):
+        self.sessionName = "default"
         self.sessionPath = "/anydb"
-        self.storageType = "anydb"
         self.persistant  = True
         self.doSession()
         self.persistant = False

cherrypy/test/test_tutorials.py

                          "\n            page 2 times! Your life is a patio of fun!"
                          "\n        ")
     
-    def test08AdvancedSessions(self):
+    def __test08AdvancedSessions(self):
         self.load_tut_module("tut08_advanced_sessions")
         cherrypy.config.update({"sessionFilter.on": True})
         
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.