|
| 1 | +"""This module defines a very basic store that's used by the CGI interface |
| 2 | +to store session and one-time-key information. |
| 3 | +
|
| 4 | +Yes, it's called "sessions" - because originally it only defined a session |
| 5 | +class. It's now also used for One Time Key handling too. |
| 6 | +
|
| 7 | +We needed to split commits to session/OTK database from commits on the |
| 8 | +main db structures (user data). This required two connections to the |
| 9 | +sqlite db, which wasn't supported. This module was created so sqlite |
| 10 | +didn't have to use dbm for the session/otk data. It hopefully will |
| 11 | +provide a performance speedup. |
| 12 | +""" |
| 13 | +__docformat__ = 'restructuredtext' |
| 14 | +import os, time, logging |
| 15 | + |
| 16 | +from roundup.anypy.html import html_escape as escape |
| 17 | + |
| 18 | +class BasicDatabase: |
| 19 | + ''' Provide a nice encapsulation of an RDBMS table. |
| 20 | +
|
| 21 | + Keys are id strings, values are automatically marshalled data. |
| 22 | + ''' |
| 23 | + name = None |
| 24 | + def __init__(self, db): |
| 25 | + self.db = db |
| 26 | + self.conn, self.cursor = self.db.sql_open_connection(dbname=self.name) |
| 27 | + |
| 28 | + self.sql('''SELECT name FROM sqlite_master WHERE type='table' AND name='%ss';'''%self.name) |
| 29 | + table_exists = self.cursor.fetchone() |
| 30 | + |
| 31 | + if not table_exists: |
| 32 | + # create table/rows etc. |
| 33 | + self.sql('''CREATE TABLE %(name)ss (%(name)s_key VARCHAR(255), |
| 34 | + %(name)s_value TEXT, %(name)s_time REAL)'''%{"name":self.name}) |
| 35 | + self.sql('CREATE INDEX %(name)s_key_idx ON %(name)ss(%(name)s_key)'%{"name":self.name}) |
| 36 | + self.commit() |
| 37 | + |
| 38 | + def log_debug(self, msg, *args, **kwargs): |
| 39 | + """Log a message with level DEBUG.""" |
| 40 | + |
| 41 | + logger = self.get_logger() |
| 42 | + logger.debug(msg, *args, **kwargs) |
| 43 | + |
| 44 | + def log_info(self, msg, *args, **kwargs): |
| 45 | + """Log a message with level INFO.""" |
| 46 | + |
| 47 | + logger = self.get_logger() |
| 48 | + logger.info(msg, *args, **kwargs) |
| 49 | + |
| 50 | + def get_logger(self): |
| 51 | + """Return the logger for this database.""" |
| 52 | + |
| 53 | + # Because getting a logger requires acquiring a lock, we want |
| 54 | + # to do it only once. |
| 55 | + if not hasattr(self, '__logger'): |
| 56 | + self.__logger = logging.getLogger('roundup') |
| 57 | + |
| 58 | + return self.__logger |
| 59 | + |
| 60 | + def sql(self, sql, args=None, cursor=None): |
| 61 | + """ Execute the sql with the optional args. |
| 62 | + """ |
| 63 | + self.log_debug('SQL %r %r' % (sql, args)) |
| 64 | + if not cursor: |
| 65 | + cursor = self.cursor |
| 66 | + if args: |
| 67 | + cursor.execute(sql, args) |
| 68 | + else: |
| 69 | + cursor.execute(sql) |
| 70 | + |
| 71 | + def clear(self): |
| 72 | + self.cursor.execute('delete from %ss'%self.name) |
| 73 | + |
| 74 | + def exists(self, infoid): |
| 75 | + n = self.name |
| 76 | + self.cursor.execute('select count(*) from %ss where %s_key=%s'%(n, |
| 77 | + n, self.db.arg), (infoid,)) |
| 78 | + return int(self.cursor.fetchone()[0]) |
| 79 | + |
| 80 | + _marker = [] |
| 81 | + def get(self, infoid, value, default=_marker): |
| 82 | + n = self.name |
| 83 | + self.cursor.execute('select %s_value from %ss where %s_key=%s'%(n, |
| 84 | + n, n, self.db.arg), (infoid,)) |
| 85 | + res = self.cursor.fetchone() |
| 86 | + if not res: |
| 87 | + if default != self._marker: |
| 88 | + return default |
| 89 | + raise KeyError('No such %s "%s"'%(self.name, escape(infoid))) |
| 90 | + values = eval(res[0]) |
| 91 | + return values.get(value, None) |
| 92 | + |
| 93 | + def getall(self, infoid): |
| 94 | + n = self.name |
| 95 | + self.cursor.execute('select %s_value from %ss where %s_key=%s'%(n, |
| 96 | + n, n, self.db.arg), (infoid,)) |
| 97 | + res = self.cursor.fetchone() |
| 98 | + if not res: |
| 99 | + raise KeyError('No such %s "%s"'%(self.name, escape (infoid))) |
| 100 | + return eval(res[0]) |
| 101 | + |
| 102 | + def set(self, infoid, **newvalues): |
| 103 | + """ Store all newvalues under key infoid with a timestamp in database. |
| 104 | +
|
| 105 | + If newvalues['__timestamp'] exists and is representable as a floating point number |
| 106 | + (i.e. could be generated by time.time()), that value is used for the <name>_time |
| 107 | + column in the database. |
| 108 | + """ |
| 109 | + c = self.cursor |
| 110 | + n = self.name |
| 111 | + a = self.db.arg |
| 112 | + c.execute('select %s_value from %ss where %s_key=%s'%(n, n, n, a), |
| 113 | + (infoid,)) |
| 114 | + res = c.fetchone() |
| 115 | + if res: |
| 116 | + values = eval(res[0]) |
| 117 | + else: |
| 118 | + values = {} |
| 119 | + values.update(newvalues) |
| 120 | + |
| 121 | + if res: |
| 122 | + sql = 'update %ss set %s_value=%s where %s_key=%s'%(n, n, |
| 123 | + a, n, a) |
| 124 | + args = (repr(values), infoid) |
| 125 | + else: |
| 126 | + if '__timestamp' in newvalues: |
| 127 | + try: |
| 128 | + # __timestamp must be represntable as a float. Check it. |
| 129 | + timestamp = float(newvalues['__timestamp']) |
| 130 | + except ValueError: |
| 131 | + timestamp = time.time() |
| 132 | + else: |
| 133 | + timestamp = time.time() |
| 134 | + |
| 135 | + sql = 'insert into %ss (%s_key, %s_time, %s_value) '\ |
| 136 | + 'values (%s, %s, %s)'%(n, n, n, n, a, a, a) |
| 137 | + args = (infoid, timestamp, repr(values)) |
| 138 | + c.execute(sql, args) |
| 139 | + |
| 140 | + def list(self): |
| 141 | + c = self.cursor |
| 142 | + n = self.name |
| 143 | + c.execute('select %s_key from %ss'%(n, n)) |
| 144 | + return [res[0] for res in c.fetchall()] |
| 145 | + |
| 146 | + def destroy(self, infoid): |
| 147 | + self.cursor.execute('delete from %ss where %s_key=%s'%(self.name, |
| 148 | + self.name, self.db.arg), (infoid,)) |
| 149 | + |
| 150 | + def updateTimestamp(self, infoid): |
| 151 | + """ don't update every hit - once a minute should be OK """ |
| 152 | + now = time.time() |
| 153 | + self.cursor.execute('''update %ss set %s_time=%s where %s_key=%s |
| 154 | + and %s_time < %s'''%(self.name, self.name, self.db.arg, |
| 155 | + self.name, self.db.arg, self.name, self.db.arg), |
| 156 | + (now, infoid, now-60)) |
| 157 | + |
| 158 | + def clean(self): |
| 159 | + ''' Remove session records that haven't been used for a week. ''' |
| 160 | + now = time.time() |
| 161 | + week = 60*60*24*7 |
| 162 | + old = now - week |
| 163 | + self.cursor.execute('delete from %ss where %s_time < %s'%(self.name, |
| 164 | + self.name, self.db.arg), (old, )) |
| 165 | + |
| 166 | + def lifetime(self, key_lifetime=None): |
| 167 | + """Return the proper timestamp for a key with key_lifetime specified |
| 168 | + in seconds. |
| 169 | + """ |
| 170 | + now = time.time() |
| 171 | + week = 60*60*24*7 |
| 172 | + return now - week + lifetime |
| 173 | + |
| 174 | + def commit(self): |
| 175 | + logger = logging.getLogger('roundup.hyperdb.backend') |
| 176 | + logger.info('commit %s' % self.name) |
| 177 | + self.conn.commit() |
| 178 | + self.cursor = self.conn.cursor() |
| 179 | + |
| 180 | + def close(self): |
| 181 | + self.conn.close() |
| 182 | + |
| 183 | +class Sessions(BasicDatabase): |
| 184 | + name = 'session' |
| 185 | + |
| 186 | +class OneTimeKeys(BasicDatabase): |
| 187 | + name = 'otk' |
| 188 | + |
| 189 | +# vim: set et sts=4 sw=4 : |
0 commit comments