1 #$Id: sessions.py,v 1.3 2002-09-10 00:11:50 richard Exp $
2 '''
3 This module defines a very basic store that's used by the CGI interface
4 to store session information.
5 '''
7 import anydbm, whichdb, os, marshal
9 class Sessions:
10 ''' Back onto an anydbm store.
12 Keys are session id strings, values are marshalled data.
13 '''
14 def __init__(self, config):
15 self.config = config
16 self.dir = config.DATABASE
17 # ensure files are group readable and writable
18 os.umask(0002)
20 def clear(self):
21 path = os.path.join(self.dir, 'sessions')
22 if os.path.exists(path):
23 os.remove(path)
24 elif os.path.exists(path+'.db'): # dbm appends .db
25 os.remove(path+'.db')
27 def determine_db_type(self, path):
28 ''' determine which DB wrote the class file
29 '''
30 db_type = ''
31 if os.path.exists(path):
32 db_type = whichdb.whichdb(path)
33 if not db_type:
34 raise hyperdb.DatabaseError, "Couldn't identify database type"
35 elif os.path.exists(path+'.db'):
36 # if the path ends in '.db', it's a dbm database, whether
37 # anydbm says it's dbhash or not!
38 db_type = 'dbm'
39 return db_type
41 def get(self, sessionid, value):
42 db = self.opendb('c')
43 try:
44 if db.has_key(sessionid):
45 values = marshal.loads(db[sessionid])
46 else:
47 return None
48 return values.get(value, None)
49 finally:
50 db.close()
52 def set(self, sessionid, **newvalues):
53 db = self.opendb('c')
54 try:
55 if db.has_key(sessionid):
56 values = marshal.loads(db[sessionid])
57 else:
58 values = {}
59 values.update(newvalues)
60 db[sessionid] = marshal.dumps(values)
61 finally:
62 db.close()
64 def list(self):
65 db = self.opendb('r')
66 try:
67 return db.keys()
68 finally:
69 db.close()
71 def destroy(self, sessionid):
72 db = self.opendb('c')
73 try:
74 if db.has_key(sessionid):
75 del db[sessionid]
76 finally:
77 db.close()
79 def opendb(self, mode):
80 '''Low-level database opener that gets around anydbm/dbm
81 eccentricities.
82 '''
83 # figure the class db type
84 path = os.path.join(os.getcwd(), self.dir, 'sessions')
85 db_type = self.determine_db_type(path)
87 # new database? let anydbm pick the best dbm
88 if not db_type:
89 return anydbm.open(path, 'c')
91 # open the database with the correct module
92 dbm = __import__(db_type)
93 return dbm.open(path, mode)
95 def commit(self):
96 pass