Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

Changeset 375

Show
Ignore:
Timestamp:
06/24/05 11:39:20
Author:
mikerobi
Message:

new getObjectTrail function, simplified session configuration

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/cherrypy/_cpconfig.py

    r357 r375  
    3434    'server.threadPool': 0, 
    3535 
    36     'session.storageType': 'ram', 
    37     'session.timeout': 60, 
    38     'session.cleanUpDelay': 60, 
    39     'session.cookieName': 'CherryPySession', 
    40     'session.storageFileDir': '', 
     36    'sessionFilter.on' : False, 
    4137     
    42     'sessionFilter.on': False, 
    43     'sessionFilter.timeout': 60, 
    44     'sessionFilter.cleanUpDelay': 60, 
    45     'sessionFilter.storageType' : 'ram', 
    46     'sessionFilter.cookieName': 'CherryPySession', 
    47     'sessionFilter.storageFileDir': '.sessionFiles', 
    48      
    49     'sessionFilter.new': 'sessionMap', # legacy setting 
     38    'sessionFilter.default.on': True, 
     39    'sessionFilter.default.timeout': 60, 
     40    'sessionFilter.default.cleanUpDelay': 60, 
     41    'sessionFilter.default.storageType' : 'ram', 
     42    'sessionFilter.default.cookieName': 'CherryPySession', 
     43    'sessionFilter.default.storageFileDir': '.sessionFiles' 
    5044    } 
    5145 
  • trunk/cherrypy/_cputil.py

    r343 r375  
    4040 
    4141 
    42 def getSpecialAttribute(name): 
    43     """ Return the special function """ 
    44      
    45     # First, we look in the right-most object if this special function is implemented. 
    46     # If not, then we try the previous object and so on until we reach cpg.root 
    47     # If it's still not there, we use the implementation from this module. 
    48      
     42def getObjectTrail(): 
     43    """ Return all objects from the currenct object to cpg """ 
    4944    root = getattr(cpg, 'root', None) 
    5045    if root: 
    51         moduleList = [root] 
     46        objectTrail = [cpg, root] 
    5247        # Try object path 
    5348        try: 
     
    6257                try: 
    6358                    root = getattr(root, newObj) 
    64                     moduleList.append(root) 
     59                    objectTrail.append(root) 
    6560                except AttributeError: 
    6661                    break 
    6762         
    68         moduleList.reverse() 
    69         for module in moduleList: 
    70             func = getattr(module, name, None) 
    71             if func != None: 
    72                 return func 
     63        return objectTrail 
     64    return None 
     65 
     66def getSpecialAttribute(name): 
     67    """ Return the special attribute """ 
     68     
     69    # First, we look in the right-most object if this special attribute is implemented. 
     70    # If not, then we try the previous object and so on until we reach cpg.root 
     71    # If it's still not there, we use the implementation from this module. 
     72     
     73    objectList = getObjectTrail() 
     74    if objectList: 
     75         
     76        objectList.reverse() 
     77        for obj in objectList: 
     78            attr = getattr(obj, name, None) 
     79            if attr != None: 
     80                return attr 
    7381     
    7482    try: 
  • trunk/cherrypy/lib/filter/sessionfilter/basesession.py

    r303 r375  
    105105            self.__sessionCache[sessionKey] = session 
    106106         
    107         if self.sessionName == 'sessionMap': 
    108             # raise a warning perhaps 
    109             setattr(cpg.request, self.sessionName, session) 
    110107        setattr(cpg.sessions, self.sessionName, session) 
    111108 
  • trunk/cherrypy/lib/filter/sessionfilter/dbmsession.py

    r298 r375  
    3535from simplesessiondict import SimpleSessionDict 
    3636 
     37import os.path 
     38 
    3739class DBMSession(BaseSession): 
    3840    def __init__(self, sessionName): 
     
    4143        BaseSession.__init__(self, sessionName) 
    4244         
    43         sessionName=cpg.config.get('sessionFilter.new', None) 
    44         sessionFile=cpg.config.get('%s.dbFile' % sessionName, '%s.db' % sessionName) 
     45        # we must make sure the db file is unique 
     46        defaultFile = '%s-%i.db' % (sessionName, hash(self)) 
     47        dbFilePrefix=cpg.config.get('sessionFilter.%s.dbFilePrefix' % sessionName, '') 
     48 
     49        sessionFile = os.path.join(dbFilePrefix, defaultFile) 
     50         
    4551        self.__data = shelve.open(sessionFile, 'c') 
    4652     
  • trunk/cherrypy/lib/filter/sessionfilter/filesession.py

    r346 r375  
    4747    def __storageDir(self): 
    4848        cpg = cherrypy.cpg 
    49         storageDir = sessionconfig.retrieve('storageFileDir', self.sessionName, '.sessionFiles') 
     49         
     50        storageDir = sessionconfig.retrieve('storageFileDir', self.sessionName)  
    5051        return storageDir 
    5152     
  • trunk/cherrypy/lib/filter/sessionfilter/sessionconfig.py

    r282 r375  
    4949def retrieve(keyName, sessionName, default = None): 
    5050    cpg = cherrypy.cpg 
    51     value = cpg.config.get('%s.%s' % (sessionName, keyName), None
    52     if value == None: 
    53         value = cpg.config.get('sessionFilter.%s' % keyName, None) 
    54  
     51    missing = object(
     52    value = cpg.config.get('sessionFilter.%s.%s' % (sessionName, keyName), missing) 
     53    if value is missing: 
     54        value = cpg.config.get('sessionFilter.default.%s' % keyName, default) 
    5555    return value 
  • trunk/cherrypy/lib/filter/sessionfilter/sessionerrors.py

    r275 r375  
    3838    """ Possibly raised a browser sends a none with a session idwhen the sessions Expire """ 
    3939 
     40class SessionIncompatibleError(SessionError): 
     41    """ raised if the configured storage type is not compatible with the application """ 
     42 
    4043class SessionImmutableError(SessionError): 
    4144    """ immutable exception """ 
  • trunk/cherrypy/lib/filter/sessionfilter/sessionfilter.py

    r319 r375  
    11 
    2 from cherrypy.lib.filter.basefilter import BaseFilter 
    32import cherrypy.cpg 
    43 
    5 import time, re 
     4import time 
    65 
    7 from sessionerrors import SessionNotFoundError  
     6from sessionerrors import SessionNotFoundError, SessionIncompatibleError 
    87 
    98import sessionconfig  
     9from cherrypy._cputil import getObjectTrail 
    1010 
    11 def _getSessions(): 
    12     """ checks the config file for the sessions """ 
    13     cpg = cherrypy.cpg 
     11def _getSessions2(): 
     12    cpg =cherrypy.cpg 
     13    sessions = {} 
     14 
     15    objectTrail = getObjectTrail() 
    1416     
    15     sessions = {} 
     17    for n in xrange(len(objectTrail)): 
     18        obj = objectTrail[n] 
     19        objPath = '/'.join(cpg.request.path.split('/')[0:n+1]) 
     20        if not objPath: 
     21            objPath = '/' 
     22 
     23        try: 
     24            sessionList = obj._cpSessionList 
     25        except AttributeError: 
     26             
     27            if obj == cpg: 
     28                obj._cpSessionList = [{'sessionName':'default'}] 
     29                sessionList = obj._cpSessionList 
     30            else: 
     31                sessionList = [] 
     32             
     33        for sessionIndex in xrange(len(sessionList)): 
     34            sessionManager = sessionList[sessionIndex] 
     35             
     36 
     37            if isinstance(sessionManager, dict): 
     38                # must be initilized 
     39                sessionName   = sessionManager['sessionName'] 
     40                compatible    = sessionManager.get('compatible',  []) 
     41                incompatible  = sessionManager.get('icompatible', []) 
     42                
     43                # unless it is off initilize 
     44                if cpg.config.get('sessionFilter.%s.on' % sessionName, True): 
     45                     
     46                    storageType = sessionconfig.retrieve('storageType', sessionName) 
    1647     
    17     sessionNames = cpg.config.getAll('sessionFilter.new') 
    18     for sessionPath in sessionNames: 
    19         sessionName = sessionNames[sessionPath] 
    20         sessionManager = cpg.config.get('%s.sessionManager' % sessionName, None) 
    21         if not sessionManager: 
    22             storageType = sessionconfig.retrieve('storageType', sessionName) 
     48                    if compatible and not storageType in compatible or \ 
     49                       incompatible and not storageType in incompatible: 
     50                        raise SessionIncompatibleError 
     51                     
     52                    sessionManager = sessionconfig._sessionTypes[storageType](sessionName) 
     53                    sessionManager.lastCleanUp = time.time() 
     54                    sessionManager.path = objPath 
     55     
     56                    obj._cpSessionList[sessionIndex] = sessionManager 
     57 
     58            elif isinstance(sessionManager, str): 
     59                # unless it is off initilize 
     60                if cpg.config.get('sessionFilter.%s.on' % sessionManager, True): 
     61                    storageType = sessionconfig.retrieve('storageType', sessionManager) 
     62                    sessionManager = sessionconfig._sessionTypes[storageType](sessionManager) 
     63                    sessionManager.lastCleanUp = time.time() 
     64                     
     65                    sessionManager.path = objPath 
     66                    obj._cpSessionList[sessionIndex] = sessionManager 
     67                 
    2368             
    24             try: 
    25                 sessionManager = sessionconfig._sessionTypes[storageType](sessionName) 
    26             except KeyError: 
    27                 storageType = cpg.config.get('%s.customStorageClass' % sessionName) 
    28                 if storageType: 
    29                     try: 
    30                         storageClass = cherrypy._cputil.getSpecialAttribute(storageType) 
    31                         sessionManager = storageClass(sessionName) 
    32                     except cherrypy.cperror.InternalError: 
    33                         raise SessionBadStorageTypeError(storageType) 
    34                 raise 
     69            else: # try and clean up 
     70                cleanUpDelay = sessionconfig.retrieve('cleanUpDelay', sessionManager.sessionName) 
     71                now = time.time() 
     72                lastCleanUp = sessionManager.lastCleanUp 
     73                if lastCleanUp + cleanUpDelay * 60 <= now: 
     74                    sessionManager.cleanUpOldSessions() 
    3575             
    36             sessionManager.path = sessionPath 
    37             sessionManager.name = sessionName 
    38             sessionManager.lastCleanUp = time.time() 
    39              
    40             cpg.config.update( 
    41                               { 
    42                                 sessionPath : {'%s.sessionManager' % sessionName : sessionManager} 
    43                               } 
    44                              ) 
    45         else: # try and clean up 
    46             cleanUpDelay = sessionconfig.retrieve('cleanUpDelay', sessionName) 
    47             now = time.time() 
    48             lastCleanUp = sessionManager.lastCleanUp 
    49             if lastCleanUp + cleanUpDelay * 60 <= now: 
    50                 sessionManager.cleanUpOldSessions() 
    51            
    52         sessions[sessionName] = sessionManager 
     76            sessions[sessionManager.sessionName] = sessionManager 
    5377     
    5478    return sessions 
    5579 
    56 class SessionFilter(BaseFilter)
     80class SessionFilter
    5781    """ 
    5882    Input filter - get the sessionId (or generate a new one) and load up the session data 
    5983    """ 
    60          
     84  
    6185    def __initSessions(self): 
    6286        cpg = cherrypy.cpg 
    63         sessions = _getSessions() 
     87        sessions = _getSessions2() 
     88#        sessions = _getSessions() 
    6489        sessionKeys = self.getSessionKeys() 
    6590         
     
    7398               sessionManager.loadSession(newKey) 
    7499                
    75                self.setSessionKey(newKey, sessionManager.name)  
     100               self.setSessionKey(newKey, sessionManager)  
    76101                 
    77102    def getSessionKeys(self): 
     
    82107         
    83108        sessionKeys= {} 
    84          
    85         sessions = cpg.config.getAll('sessionFilter.new') 
    86         for sessionPath in sessions: 
    87             sessionName = sessions[sessionPath] 
    88             cookieName = cpg.config.get('%s.cookieName' % sessionName, None) 
    89             if not cookieName: 
    90                 cookieName = (cpg.config.get('sessionFilter.cookieName') + 
    91                               '|' + sessionName + 
    92                               '|' + re.sub('/','_', sessionPath)) 
    93                 cpg.config.update({ 
    94                                     sessionPath : {'%s.cookieName' % sessionName : cookieName} 
    95                                   }) 
     109        sessions = _getSessions2() 
     110        for sessionName in sessions: 
     111            sessionManager = sessions[sessionName] 
     112 
     113            cookiePrefix = sessionconfig.retrieve('cookieName', sessionName, None) 
     114             
     115            cookieName = '%s_%s_%i' % (cookiePrefix, sessionName, hash(sessionManager)) 
     116             
    96117            try: 
    97118                sessionKeys[sessionName] = cpg.request.simpleCookie[cookieName].value 
     
    99120                sessionKeys[sessionName] = None 
    100121        return sessionKeys 
     122       
    101123 
    102     def setSessionKey(self, sessionKey, sessionName): 
     124    def setSessionKey(self, sessionKey, sessionManager): 
    103125        """  
    104126        Sets the session key in a cookie.  Aplications should not call this function, 
     
    108130        cpg = cherrypy.cpg 
    109131         
    110         cookieName = cpg.config.get('%s.cookieName' % sessionName, None) 
     132        sessionName = sessionManager.sessionName 
     133         
     134        cookiePrefix = sessionconfig.retrieve('cookieName', sessionName, None) 
     135         
     136        cookieName = '%s_%s_%i' % (cookiePrefix, sessionName, hash(sessionManager)) 
    111137 
    112138        cpg.response.simpleCookie[cookieName] = sessionKey 
    113139        cpg.response.simpleCookie[cookieName]['version'] = 1 
    114  
    115         path = cpg.config.get('%s.sessionManager' % sessionName, returnSection = True) 
    116         cpg.response.simpleCookie[cookieName]['path'] = path 
     140         
     141        cpg.response.simpleCookie[cookieName]['path'] = sessionManager.path 
    117142 
    118143     
    119144    def __saveSessions(self): 
    120145        cpg = cherrypy.cpg 
    121         sessions = _getSessions() 
     146        #sessions = _getSessions() 
     147        sessions = _getSessions2() 
    122148         
    123149        for sessionName in sessions: 
     
    128154    def beforeMain(self): 
    129155        cpg = cherrypy.cpg 
    130         if (cpg.config.get('sessionFilter.on', False) 
    131             and not cpg.config.get('staticFilter.on', False)): 
     156        if not cpg.config.get('staticFilter.on', False) and \ 
     157            cpg.config.get('sessionFilter.on'): 
    132158           self.__initSessions() 
    133159 
    134160    def beforeFinalize(self): 
    135161        cpg = cherrypy.cpg 
    136         if (cpg.config.get('sessionFilter.on', False) 
    137             and not cpg.config.get('staticFilter.on', False)): 
     162        if not cpg.config.get('staticFilter.on', False) and \ 
     163            cpg.config.get('sessionFilter.on'): 
    138164            self.__saveSessions() 
    139165 
     
    141167    #this breaks a test case 
    142168    def beforeErrorResponse(self): 
     169        cpg = cherrypy.cpg 
    143170        # Still save session data 
    144         if (cpg.config.get('sessionFilter.on', False) 
    145             and not cpg.config.get('staticFilter.on', False)): 
    146             self.__saveSessions() 
     171        if not cpg.config.get('staticFilter.on', False) and \ 
     172            cpg.config.get('sessionFilter.on'): 
    147173    ''' 
  • trunk/cherrypy/test/test_tutorials.py

    r366 r375  
    129129                         'Hendrik Mans, CherryPy co-developer & crazy German ' 
    130130                         '(<a href="./">back</a>)') 
    131      
    132131    def test07Sessions(self): 
    133132        load_tut_module("tut07_sessions") 
     
    154153                         'Remi<br/>Carlos<br/>Hendrik<br/>Lorenzo Lamas<br/>' 
    155154                         '</body></html>') 
    156      
    157155    def test09SessionFilter(self): 
    158156        load_tut_module("tut09_sessionfilter") 
  • trunk/cherrypy/tutorial/tut07_sessions.py

    r341 r375  
    1515    def index(self): 
    1616        # Increase the silly hit counter 
    17         count = cpg.request.sessionMap.get('count', 0) + 1 
     17        count = cpg.sessions.default.get('count', 0) + 1 
    1818         
    1919        # Store the new value in the session dictionary 
    20         cpg.request.sessionMap['count'] = count 
     20        cpg.sessions.default['count'] = count 
    2121         
    2222        # And display a silly hit count message! 
  • trunk/cherrypy/tutorial/tut09_sessionfilter.py

    r341 r375  
    55from cherrypy import cpg 
    66 
     7# you will never need to import the RamSession 
     8# we only import it to demostrate how to manually use 
     9# a storage adaptor as would with a customized storage adaptor 
     10from cherrypy.lib.filter.sessionfilter.ramsession import RamSession 
     11  
    712class HitCounter: 
    8    
     13    _cpSessionList=[] 
     14    # this list will contain site wide sessions 
     15    # in almost all cases this will be defined on a class by class basis, 
     16    # but for this simple example we use a seperate session list for each method 
     17    # for simplicity 
     18 
    919    # this is just a primative template function 
    1020    def __examplePage(self, poweredBy, count, links, sessionKey): 
     
    1929        yield '\n</body></html>' 
    2030 
    21     # a list of the pages used in the example so we add pages 
     31    # a list of the pages used in the example so we can add pages 
    2232    # without changing any code 
    2333    samplePages = ['admin', 'index', 'forum'] 
    2434     
    2535    def index(self): 
    26         # this function uses the sessionMap which is turned on by defualt 
     36        # this function uses the default session 
    2737        # it may not be the defualt in future versions 
    2838         
    2939        # Increase the silly hit counter 
    30         count = cpg.sessions.sessionMap.get('count', 0) + 1 
     40        count = cpg.sessions.default.get('count', 0) + 1 
    3141 
    3242        # Store the new value in the session dictionary 
    33         # cpg.sessions.sessionMap is available by default 
    34         cpg.sessions.sessionMap['count'] = count 
     43        # cpg.sessions.default is available by default 
     44        cpg.sessions.default['count'] = count 
    3545 
    3646        # And display a silly hit count message! 
    37         key = cpg.sessions.sessionMap.key 
     47        key = cpg.sessions.default.key 
    3848        return self.__examplePage('ram', count, self.samplePages, key) 
    3949 
     
    4151 
    4252    def admin(self): 
    43         # this function uses the adminSession which is defined in 
     53        # this function uses the admin which is defined in 
    4454        # the config file "tut10_sessionFilter.conf", otherwise 
    4555        # it mirrors the session function 
    4656 
    47         adminCount = cpg.sessions.adminSession.get('adminCount', 0) + 1 
    48         cpg.sessions.adminSession['adminCount'] = adminCount 
     57        adminCount = cpg.sessions.admin.get('adminCount', 0) + 1 
     58        cpg.sessions.admin['adminCount'] = adminCount 
    4959         
    50         key = cpg.sessions.adminSession.key 
     60        key = cpg.sessions.admin.key 
    5161        return self.__examplePage('ram', adminCount, self.samplePages, key) 
     62     
    5263    admin.exposed = True 
     64    admin._cpSessionList=['admin'] 
    5365     
    5466    def forum(self): 
    55         # this function uses the forumSession which is defined in 
     67        # this function uses its own forum session which is defined in 
     68        # the  
    5669        # the config file "tut10_sessionFilter.conf", otherwise 
    5770        # it mirrors the session function 
    5871         
    59         forumCount = cpg.sessions.forumSession.get('forumCount', 0) + 1 
    60         cpg.sessions.forumSession['forumCount'] = forumCount 
     72        forumCount = cpg.sessions.forum.get('forumCount', 0) + 1 
     73        cpg.sessions.forum['forumCount'] = forumCount 
    6174         
    62         key = cpg.sessions.forumSession.key 
     75        key = cpg.sessions.forum.key 
    6376        return self.__examplePage('ram', forumCount, self.samplePages, key) 
     77     
    6478    forum.exposed=True 
     79    forum._cpSessionList=['forum'] 
    6580 
    6681cpg.root = HitCounter() 
    6782 
    6883if __name__ == '__main__': 
     84    cpg.config.update(file = "tutorial.conf") 
    6985    cpg.config.update(file = 'tut10_sessionfilter.conf') 
    7086    cpg.server.start() 

Hosted by WebFaction

Log in as guest/cpguest to create tickets