1 from bson.objectid import ObjectId
2 from concurrent.futures import ThreadPoolExecutor
7 class MemCursor(object):
8 def __init__(self, collection):
9 self.collection = collection
10 self.count = len(self.collection)
12 def _is_next_exist(self):
13 return self.count != 0
17 with ThreadPoolExecutor(max_workers=2) as executor:
18 result = executor.submit(self._is_next_exist)
21 def next_object(self):
23 return self.collection.pop()
32 def _find_one(self, spec_or_id=None, *args):
33 if spec_or_id is not None and not isinstance(spec_or_id, dict):
34 spec_or_id = {"_id": spec_or_id}
35 cursor = self._find(spec_or_id, *args)
40 def find_one(self, spec_or_id=None, *args):
41 with ThreadPoolExecutor(max_workers=2) as executor:
42 result = executor.submit(self._find_one, spec_or_id, *args)
45 def _insert(self, doc_or_docs):
49 if isinstance(docs, dict):
56 doc['_id'] = ObjectId()
57 if not self._find_one(doc['_id']):
58 ids.append(doc['_id'])
59 self.contents.append(doc_or_docs)
68 def insert(self, doc_or_docs):
69 with ThreadPoolExecutor(max_workers=2) as executor:
70 result = executor.submit(self._insert, doc_or_docs)
74 def _in(content, *args):
76 for k, v in arg.iteritems():
77 if content.get(k, None) != v:
82 def _find(self, *args):
84 for content in self.contents:
85 if self._in(content, *args):
90 def find(self, *args):
91 return MemCursor(self._find(*args))
93 def _update(self, spec, document):
95 for index in range(len(self.contents)):
96 content = self.contents[index]
97 if self._in(content, spec):
98 for k, v in document.iteritems():
101 self.contents[index] = content
104 def update(self, spec, document):
105 with ThreadPoolExecutor(max_workers=2) as executor:
106 result = executor.submit(self._update, spec, document)
109 def _remove(self, spec_or_id=None):
110 if spec_or_id is None:
112 if not isinstance(spec_or_id, dict):
113 spec_or_id = {'_id': spec_or_id}
114 for index in range(len(self.contents)):
115 content = self.contents[index]
116 if self._in(content, spec_or_id):
117 del self.contents[index]
121 def remove(self, spec_or_id=None):
122 with ThreadPoolExecutor(max_workers=2) as executor:
123 result = executor.submit(self._remove, spec_or_id)
130 test_projects = MemDb()
132 test_results = MemDb()