Not sure if anyone else would have a use for this, but I needed a persistent
mapping interface to substitute in existing python code (non-pickle). I
imagine there might be a more elegant way to do this (maybe using
meta-classes?), and I'd love to hear any feedback on it.
-Charles
----------------------------> code below
<--------------------------------------
from SQLObject import *
class StickyMap (dict):
#StickyDict seemed inappropriate... ;)
"""
This object will map a (simple) dictionary to SQLObjects.
Both keys and values will be strings (or values configured in items)
"""
def __init__(self, connection):
# could pass connection in here in order to use on different threads
self.conn = connection
# maybe use dict for caching already initialized sqlobjects?
# will not want this if more than one thread is updating the
database?
# (get a fresh copy every time then)
self._dict = {}
def get (self, key, default=None):
items = StickyMapItem.select(StickyMapItem.q.dkey == key,
connection=self.conn)
if items.count():
val = items[0].value
else:
val = default
return val
def __getitem__(self, key):
item = StickyMapItem.byDkey(key, connection=self.conn)
return item.dvalue # if no dvalue, exception raised
def __setitem__(self, key, value):
dict = {}
items = StickyMapItem.select(StickyMapItem.q.dkey == key,
connection=self.conn)
if items.count():
dict[key] = items[0]
dict[key].set(dvalue=value)
else:
dict[key] = StickyMapItem.new(dkey=key, dvalue=value,
_connection=self.conn)
def __delitem__(self, key):
StickyMapItem.byDkey(key, connection=self.conn).destroySelf()
def __len__(self):
return StickyMapItem.select(connection=self.conn).count()
def has_key (self, key):
items = StickyMapItem.select(StickyMapItem.q.dkey == key,
connection=self.conn)
if items.count():
return True
else:
return False
### these are implemented to be consistent with the mapping object
### interface, but may be resource intensive on large tables?
def _get_all(self):
dict = {}
items = StickyMapItem.select(connection=self.conn)
for item in items:
dict[item.dkey] = item.dvalue
return dict
def values(self):
dict = self._get_all()
return dict.values()
def items(self):
dict = self._get_all()
return dict.items()
def keys(self):
dict = self._get_all()
return dict.keys()
class StickyMapItem(SQLObject):
"""
table to store persistent dictionary items
the only catch is that the table will be named by this class
seems to indicate the need for a meta class implementation
(something to replace the customized item class in the StickyMap logic)
NOTE:
"key" is a sql keyword that doesn't get quoted properly in dbconnection
"""
# for now just using a string
# eventually a join sqlobject type to another object
#
dvalue = StringCol(alternateID=True, unique=True, length=255)
dkey = StringCol(alternateID=True, unique=True, length=255)
|