Package grassyknoll :: Package backend :: Package dictionary :: Module DictCollection
[hide private]

Source Code for Module grassyknoll.backend.dictionary.DictCollection

 1  """L{dict} based collection""" 
 2  import cPickle 
 3  import os.path 
 4   
 5  from grassyknoll.collection import Collection 
 6   
7 -class DictCollection(Collection.Collection):
8 """an in-memory collection""" 9
10 - def __init__(self, data=None):
11 self.data=data if data is not None else {}
12
13 - def __len__(self):
14 return len(self.data)
15 16 @Collection.addMetaData
17 - def list(self):
18 return Collection.CollectionIds(self.data.keys())
19 20 @Collection.addMetaData
21 - def create(self, docs):
22 for doc in docs: 23 self.data[doc.id]=doc 24 return Collection.CollectionIds([doc.id for doc in docs])
25 26 @Collection.addMetaData
27 - def delete(self, ids):
28 for uid in ids: 29 self.data.pop(uid, None) 30 return Collection.CollectionIds(ids)
31 32 @Collection.addMetaData
33 - def retrieve(self, ids, fields=None):
34 results=[] 35 for uid in ids: 36 doc=self.data.get(uid) 37 if doc is not None: 38 assert isinstance(doc, Collection.CollectionDocument) 39 if fields is None: 40 res=Collection.CollectionResult(doc) 41 else: 42 if '__id__' not in fields: fields+=('__id__',) 43 res=Collection.CollectionResult(dict((k, v) for k, v 44 in doc.iteritems() 45 if k in fields)) 46 results.append(res) 47 48 return Collection.CollectionResultSet(results)
49 50 # no point testing this
51 -class PersistentDictCollection(DictCollection): #pragma: no cover
52 """a L{DictCollection} that saves to a pickle""" 53
54 - def __init__(self, fname):
55 super(PersistentDictCollection, self).__init__() 56 self.fname=fname 57 if os.path.exists(fname): 58 self.data=cPickle.load(file(fname, 'r')) 59 assert isinstance(self.data, dict)
60
61 - def close(self):
62 cPickle.dump(self.data, file(self.fname, 'w'), -1)
63