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 cursor = self._find(spec_or_id, *args)
41 def find_one(self, spec_or_id=None, *args):
42 with ThreadPoolExecutor(max_workers=2) as executor:
43 result = executor.submit(self._find_one, spec_or_id, *args)
46 def _insert(self, doc_or_docs, check_keys=True):
50 if isinstance(docs, dict):
57 doc['_id'] = str(ObjectId())
58 if not check_keys or not self._find_one(doc['_id']):
59 ids.append(doc['_id'])
60 self.contents.append(doc_or_docs)
69 def insert(self, doc_or_docs, check_keys=True):
70 with ThreadPoolExecutor(max_workers=2) as executor:
71 result = executor.submit(self._insert, doc_or_docs, check_keys)
75 def _in(content, *args):
77 for k, v in arg.iteritems():
78 if k != 'creation_date' and content.get(k, None) != v:
83 def _find(self, *args):
85 for content in self.contents:
86 if self._in(content, *args):
91 def find(self, *args):
92 return MemCursor(self._find(*args))
94 def _update(self, spec, document):
96 for index in range(len(self.contents)):
97 content = self.contents[index]
98 if self._in(content, spec):
99 for k, v in document.iteritems():
102 self.contents[index] = content
105 def update(self, spec, document):
106 with ThreadPoolExecutor(max_workers=2) as executor:
107 result = executor.submit(self._update, spec, document)
110 def _remove(self, spec_or_id=None):
111 if spec_or_id is None:
113 if not isinstance(spec_or_id, dict):
114 spec_or_id = {'_id': spec_or_id}
115 for index in range(len(self.contents)):
116 content = self.contents[index]
117 if self._in(content, spec_or_id):
118 del self.contents[index]
122 def remove(self, spec_or_id=None):
123 with ThreadPoolExecutor(max_workers=2) as executor:
124 result = executor.submit(self._remove, spec_or_id)