Back to index

python-weblib  1.3.9
Public Member Functions | Public Attributes | Private Member Functions | Private Attributes
pyweblib.session.WebSession Class Reference

List of all members.

Public Member Functions

def __init__
def sync
def close
def storeSession
def deleteSession
def retrieveSession
def newSession
def cleanUp

Public Attributes

 sessiondict
 expireDeactivate
 expireRemove
 crossCheckVars
 maxSessionCount
 sessionCounter
 session_id_len
 session_id_chars
 session_id_re

Private Member Functions

def _validateSessionIdFormat
def _crosscheckSessionEnv
def _generateCrosscheckEnv
def _generateSessionID

Private Attributes

 _session_lock

Detailed Description

The session class which handles storing and retrieving of session data
in a dictionary-like sessiondict object.

Definition at line 154 of file session.py.


Constructor & Destructor Documentation

def pyweblib.session.WebSession.__init__ (   self,
  dictobj = None,
  expireDeactivate = 0,
  expireRemove = 0,
  crossCheckVars = None,
  maxSessionCount = None,
  sessionIDLength = 12,
  sessionIDChars = None 
)
dictobj
has to be a instance of a dictionary-like object
(e.g. derived from UserDict or shelve)
expireDeactivate
amount of time (secs) after which a session
expires and a SessionExpired exception is
raised which contains the session data.
expireRemove
Amount of time (secs) after which a session
expires and the session data is silently deleted.
A InvalidSessionId exception is raised in this case if
the application trys to access the session ID again.
crossCheckVars
List of keys of variables cross-checked for each
retrieval of session data in retrieveSession(). If None
SESSION_CROSSCHECKVARS is used.
maxSessionCount
Maximum number of valid sessions. This affects
behaviour of retrieveSession() which raises.
None means unlimited number of sessions.
sessionIDLength
Exact integer length of the session ID generated
sessionIDChars
String containing the valid chars for session IDs
(if this is zero-value the default is SESSION_ID_CHARS)

Definition at line 169 of file session.py.

00169 
00170   ):
00171     """
00172     dictobj
00173         has to be a instance of a dictionary-like object
00174         (e.g. derived from UserDict or shelve)
00175     expireDeactivate
00176         amount of time (secs) after which a session
00177         expires and a SessionExpired exception is
00178         raised which contains the session data.
00179     expireRemove
00180         Amount of time (secs) after which a session
00181         expires and the session data is silently deleted.
00182         A InvalidSessionId exception is raised in this case if
00183         the application trys to access the session ID again.
00184     crossCheckVars
00185         List of keys of variables cross-checked for each
00186         retrieval of session data in retrieveSession(). If None
00187         SESSION_CROSSCHECKVARS is used.
00188     maxSessionCount
00189         Maximum number of valid sessions. This affects
00190         behaviour of retrieveSession() which raises.
00191         None means unlimited number of sessions.
00192     sessionIDLength
00193         Exact integer length of the session ID generated
00194     sessionIDChars
00195         String containing the valid chars for session IDs
00196         (if this is zero-value the default is SESSION_ID_CHARS)
00197     """
00198     if dictobj is None:
00199       self.sessiondict = {}
00200     else:
00201       self.sessiondict = dictobj
00202     self.expireDeactivate = expireDeactivate
00203     self.expireRemove = expireRemove
00204     self._session_lock = ThreadingLock()
00205     if crossCheckVars is None:
00206       crossCheckVars = SESSION_CROSSCHECKVARS
00207     self.crossCheckVars = crossCheckVars
00208     self.maxSessionCount = maxSessionCount
00209     self.sessionCounter = 0
00210     self.session_id_len = sessionIDLength
00211     self.session_id_chars = sessionIDChars or SESSION_ID_CHARS
00212     self.session_id_re = re.compile('^[%s]+$' % (re.escape(self.session_id_chars)))
00213     return # __init__()


Member Function Documentation

def pyweblib.session.WebSession._crosscheckSessionEnv (   self,
  stored_env,
  current_env 
) [private]
Returns a list of keys of items which differ in
stored_env and current_env.

Definition at line 241 of file session.py.

00241 
00242   def _crosscheckSessionEnv(self,stored_env,current_env):
00243     """
00244     Returns a list of keys of items which differ in
00245     stored_env and current_env.
00246     """
00247     return [
00248       k
00249       for k in stored_env.keys()
00250       if stored_env[k]!=current_env.get(k,None)
00251     ]

Here is the caller graph for this function:

def pyweblib.session.WebSession._generateCrosscheckEnv (   self,
  current_env 
) [private]
Generate a dictionary of env vars for session cross-checking

Definition at line 252 of file session.py.

00252 
00253   def _generateCrosscheckEnv(self,current_env):
00254     """
00255     Generate a dictionary of env vars for session cross-checking
00256     """
00257     crosscheckenv = {}
00258     for k in self.crossCheckVars:
00259       if current_env.has_key(k):
00260         crosscheckenv[k] = current_env[k]
00261     return crosscheckenv

Here is the caller graph for this function:

def pyweblib.session.WebSession._generateSessionID (   self,
  maxtry = 1 
) [private]
Generate a new random and unique session id string

Definition at line 262 of file session.py.

00262 
00263   def _generateSessionID(self,maxtry=1):
00264     """
00265     Generate a new random and unique session id string
00266     """
00267     def choice_id():
00268       return ''.join([ random.choice(SESSION_ID_CHARS) for i in range(self.session_id_len) ])
00269     newid = choice_id()
00270     tried = 0
00271     while self.sessiondict.has_key(newid) and (not maxtry or tried<maxtry):
00272       newid = choice_id()
00273       tried = tried+1
00274     if maxtry and tried>=maxtry:
00275       raise GenerateIDError(maxtry)
00276     else:
00277       return newid

Here is the caller graph for this function:

def pyweblib.session.WebSession._validateSessionIdFormat (   self,
  session_id 
) [private]
Validate the format of session_id. Implementation
has to match IDs produced in method _generateSessionID()

Definition at line 232 of file session.py.

00232 
00233   def _validateSessionIdFormat(self,session_id):
00234     """
00235     Validate the format of session_id. Implementation
00236     has to match IDs produced in method _generateSessionID()
00237     """
00238     if len(session_id)!=self.session_id_len or self.session_id_re.match(session_id) is None:
00239       raise BadSessionId(session_id)
00240     return

Here is the caller graph for this function:

Search for expired session entries and delete them.

Returns integer counter of deleted sessions as result.

Definition at line 374 of file session.py.

00374 
00375   def cleanUp(self):
00376     """
00377     Search for expired session entries and delete them.
00378 
00379     Returns integer counter of deleted sessions as result.
00380     """
00381     current_time = time.time()
00382     result = 0
00383     for session_id in self.sessiondict.keys():
00384       if not session_id.startswith('__'):
00385         try:
00386           session_timestamp = self.sessiondict[session_id][0]
00387         except InvalidSessionId:
00388           # Avoid race condition. The session might have been
00389           # deleted in the meantime. But make sure everything is deleted.
00390           self.deleteSession(session_id)
00391         else:
00392           # Check expiration time
00393           if session_timestamp+self.expireRemove<current_time:
00394             self.deleteSession(session_id)
00395             result += 1
00396     return result
00397 
00398 # Initialization
00399 random.seed()

Here is the call graph for this function:

Call close() if self.sessiondict has .close() method

Definition at line 221 of file session.py.

00221 
00222   def close(self):
00223     """
00224     Call close() if self.sessiondict has .close() method
00225     """
00226     if hasattr(self.sessiondict,'close'):
00227       # Close e.g. a database
00228       self.sessiondict.close()
00229     else:
00230       # Make sessiondict inaccessible
00231       self.sessiondict = None

def pyweblib.session.WebSession.deleteSession (   self,
  session_id 
)
Delete session_data referenced by session_id.

Definition at line 291 of file session.py.

00291 
00292   def deleteSession(self,session_id):
00293     """
00294     Delete session_data referenced by session_id.
00295     """
00296     # Delete the session data
00297     self._session_lock.acquire()
00298     try:
00299       if self.sessiondict.has_key(session_id):
00300         del self.sessiondict[session_id]
00301       if self.sessiondict.has_key('__session_checkvars__'+session_id):
00302         del self.sessiondict['__session_checkvars__'+session_id]
00303       self.sync()
00304     finally:
00305       self._session_lock.release()
00306     return session_id

Here is the call graph for this function:

Here is the caller graph for this function:

def pyweblib.session.WebSession.newSession (   self,
  env = {} 
)
Store session data under session id

Definition at line 349 of file session.py.

00349 
00350   def newSession(self,env={}):
00351     """
00352     Store session data under session id
00353     """
00354     if self.maxSessionCount and len(self.sessiondict)/2+1>self.maxSessionCount:
00355       raise MaxSessionCountExceeded(self.maxSessionCount)
00356     self._session_lock.acquire()
00357     try:
00358       # generate completely new session data entry
00359       session_id=self._generateSessionID(maxtry=3)
00360       # Store session data with timestamp if session ID
00361       # was created successfully
00362       self.sessiondict[session_id] = (
00363         # Current time
00364         time.time(),
00365         # Store a dummy string first
00366         '_created_',
00367       )
00368       self.sessiondict['__session_checkvars__'+session_id] = self._generateCrosscheckEnv(env)
00369       self.sync()
00370       self.sessionCounter += 1
00371     finally:
00372       self._session_lock.release()
00373     return session_id

Here is the call graph for this function:

def pyweblib.session.WebSession.retrieveSession (   self,
  session_id,
  env = {} 
)
Retrieve session data

Definition at line 307 of file session.py.

00307 
00308   def retrieveSession(self,session_id,env={}):
00309     """
00310     Retrieve session data
00311     """
00312     self._validateSessionIdFormat(session_id)
00313     session_vars_key = '__session_checkvars__'+session_id
00314     # Check if session id exists
00315     if not (
00316       self.sessiondict.has_key(session_id) and \
00317       self.sessiondict.has_key(session_vars_key)
00318     ):
00319       raise InvalidSessionId(session_id)
00320     # Read the timestamped session data
00321     try:
00322       self._session_lock.acquire()
00323       try:
00324         session_checkvars = self.sessiondict[session_vars_key]
00325         timestamp,session_data = self.sessiondict[session_id]
00326       finally:
00327         self._session_lock.release()
00328     except pickle.UnpicklingError:
00329       self.deleteSession(session_id)
00330       raise CorruptData
00331     current_time = time.time()
00332     # Check if session data is already expired
00333     if self.expireDeactivate and \
00334        (current_time>timestamp+self.expireDeactivate):
00335       # Remove session entry
00336       self.deleteSession(session_id)
00337       # Check if application should be able to allow relogin
00338       if self.expireRemove and \
00339          (current_time>timestamp+self.expireRemove):
00340         raise InvalidSessionId(session_id)
00341       else:
00342         raise SessionExpired(timestamp,session_data)
00343     failed_vars = self._crosscheckSessionEnv(session_checkvars,env)
00344     if failed_vars:
00345       # Remove session entry
00346       raise SessionHijacked(failed_vars)
00347     # Everything's ok => return the session data
00348     return session_data

Here is the call graph for this function:

def pyweblib.session.WebSession.storeSession (   self,
  session_id,
  session_data 
)
Store session_data under session_id.

Definition at line 278 of file session.py.

00278 
00279   def storeSession(self,session_id,session_data):
00280     """
00281     Store session_data under session_id.
00282     """
00283     self._session_lock.acquire()
00284     try:
00285       # Store session data with timestamp
00286       self.sessiondict[session_id] = (time.time(),session_data)
00287       self.sync()
00288     finally:
00289       self._session_lock.release()
00290     return session_id

Here is the call graph for this function:

Call sync if self.sessiondict has .sync() method

Definition at line 214 of file session.py.

00214 
00215   def sync(self):
00216     """
00217     Call sync if self.sessiondict has .sync() method
00218     """
00219     if hasattr(self.sessiondict,'sync'):
00220       self.sessiondict.sync()

Here is the caller graph for this function:


Member Data Documentation

Definition at line 203 of file session.py.

Definition at line 206 of file session.py.

Definition at line 201 of file session.py.

Definition at line 202 of file session.py.

Definition at line 207 of file session.py.

Definition at line 210 of file session.py.

Definition at line 209 of file session.py.

Definition at line 211 of file session.py.

Definition at line 208 of file session.py.

Definition at line 198 of file session.py.


The documentation for this class was generated from the following file: