1 from bson.objectid import ObjectId
2 from concurrent.futures import ThreadPoolExecutor
8 class MemCursor(object):
9 def __init__(self, collection):
10 self.collection = collection
11 self.count = len(self.collection)
13 def _is_next_exist(self):
14 return self.count != 0
18 with ThreadPoolExecutor(max_workers=2) as executor:
19 result = executor.submit(self._is_next_exist)
22 def next_object(self):
24 return self.collection.pop()
33 def _find_one(self, spec_or_id=None, *args):
34 if spec_or_id is not None and not isinstance(spec_or_id, dict):
35 spec_or_id = {"_id": spec_or_id}
36 if '_id' in spec_or_id:
37 spec_or_id['_id'] = str(spec_or_id['_id'])
38 cursor = self._find(spec_or_id, *args)
43 def find_one(self, spec_or_id=None, *args):
44 with ThreadPoolExecutor(max_workers=2) as executor:
45 result = executor.submit(self._find_one, spec_or_id, *args)
48 def _insert(self, doc_or_docs, check_keys=True):
52 if isinstance(docs, dict):
59 doc['_id'] = str(ObjectId())
60 if not check_keys or not self._find_one(doc['_id']):
61 ids.append(doc['_id'])
62 self.contents.append(doc_or_docs)
71 def insert(self, doc_or_docs, check_keys=True):
72 with ThreadPoolExecutor(max_workers=2) as executor:
73 result = executor.submit(self._insert, doc_or_docs, check_keys)
77 def _in(content, *args):
79 for k, v in arg.iteritems():
80 if k != 'creation_date' and content.get(k, None) != v:
85 def _find(self, *args):
87 for content in self.contents:
88 if self._in(content, *args):
93 def find(self, *args):
94 return MemCursor(self._find(*args))
96 def _update(self, spec, document):
98 for index in range(len(self.contents)):
99 content = self.contents[index]
100 if self._in(content, spec):
101 for k, v in document.iteritems():
104 self.contents[index] = content
107 def update(self, spec, document):
108 with ThreadPoolExecutor(max_workers=2) as executor:
109 result = executor.submit(self._update, spec, document)
112 def _remove(self, spec_or_id=None):
113 if spec_or_id is None:
115 if not isinstance(spec_or_id, dict):
116 spec_or_id = {'_id': spec_or_id}
117 for index in range(len(self.contents)):
118 content = self.contents[index]
119 if self._in(content, spec_or_id):
120 del self.contents[index]
124 def remove(self, spec_or_id=None):
125 with ThreadPoolExecutor(max_workers=2) as executor:
126 result = executor.submit(self._remove, spec_or_id)