Update of /cvsroot/tmda/tmda/contrib/cgi
In directory sc8-pr-cvs1:/tmp/cvs-serv2078

Added Files:
        Session.py 
Log Message:
Generic Python sessioning tool for use in any CGI.  Generates a random session
ID of alphanumerics and creates a temporary file to hold any session data.
Session object can be used like a Python dictionary.

Sessions are allowed to accummulate on the system and are cleaned up at random
intervals.  Sessions have a single exiration timeout and when a clean up begins,
any older sessions are automatically removed.


--- NEW FILE ---
#!/usr/bin/env python
#
# Copyright (C) 2002 Gre7g Luterman <[EMAIL PROTECTED]>
#
# This file is part of TMDA.
#
# TMDA is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.  A copy of this license should
# be included in the file COPYING.
#
# TMDA is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with TMDA; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

"Generic session handler."

import glob
import os
import pickle
import pwd
import random
import re
import string
import time

os.environ["HOME"] = pwd.getpwuid(os.geteuid())[5]

try:
    import paths
except ImportError:
    pass

from TMDA import Defaults

Rands = random.Random()

class Session:
  """Sessioning tool for use in CGI.

Resurrect an old session by passing a form with the session ID (SID) into the
constructor.  An empty object will be created if the session has expired.  A new
session will be created if the form does not specify an SID.

The session's SID is saved as member SID.

Session data is stored in the object by treating it as a dictionary.  For
example:
  A = Session(Form)
  A['key'] = value
  A.Save()
  print "http://some/url?SID=%s"; % A.SID

The Save() member saves the session's current values on disk."""
  
  def __init__(self, Form):
    "Reload an existing SID or create a new one."

    # Existing session?
    if Form.has_key("SID"):
      self.SID = Form["SID"].value

      # Valid looking session ID?
      if re.compile("^[a-zA-Z0-9]{8}$").search(self.SID):
        try:
          F = open(Defaults.CGI_SESSION_PREFIX + self.SID)
          self.Vars = pickle.load(F)
          F.close()
          self.Clean()
          return
        except:
          pass
      # Invalid ID
      else: raise ValueError
    # New session
    SessionChars = string.ascii_letters + string.digits
    self.SID = ""
    for i in range(8):
      self.SID += SessionChars[Rands.randrange(len(SessionChars))]
    self.Vars = {}
    self.Clean()

  def Clean(self):
    "This member is called automatically.  You should not need to call it."
    # Clean up?
    if Rands.random() < Defaults.CGI_CLEANUP_ODDS:
      # Go through all sessions and check a-times
      Sessions = glob.glob(Defaults.CGI_SESSION_PREFIX + "*")
      for Session in Sessions:
        try: # these commands could fail if another thread cleans simultaneously
          Stats = os.stat(Session)
          # Expired?
          if Stats[7] + Defaults.CGI_SESSION_EXP < time.time():
            os.remove(Session)
        except: pass
  
  def Save(self):
    "Save all session variables to disk."
    F = open(Defaults.CGI_SESSION_PREFIX + self.SID, "w")
    pickle.dump(self.Vars, F)
    F.close()

  def __contains__(self, a): return a in self.Vars
  def countOf(self): return len(self.Vars)
  def __delitem__(self, a): del self.Vars[a]
  def __getitem__(self, a): return self.Vars[a]
  def __setitem__(self, a, b): self.Vars[a] = b
  def keys(self): return self.Vars.keys()
  def has_key(self, a): return self.Vars.has_key(a)

_______________________________________
tmda-cvs mailing list
http://tmda.net/lists/listinfo/tmda-cvs

Reply via email to