1 from bson.objectid import ObjectId
2 from concurrent.futures import ThreadPoolExecutor
8 def thread_execute(method, *args, **kwargs):
9 with ThreadPoolExecutor(max_workers=2) as executor:
10 result = executor.submit(method, *args, **kwargs)
14 class MemCursor(object):
15 def __init__(self, collection):
16 self.collection = collection
17 self.count = len(self.collection)
19 def _is_next_exist(self):
20 return self.count != 0
24 return thread_execute(self._is_next_exist)
26 def next_object(self):
28 return self.collection.pop()
37 def _find_one(self, spec_or_id=None, *args):
38 if spec_or_id is not None and not isinstance(spec_or_id, dict):
39 spec_or_id = {"_id": spec_or_id}
40 if '_id' in spec_or_id:
41 spec_or_id['_id'] = str(spec_or_id['_id'])
42 cursor = self._find(spec_or_id, *args)
47 def find_one(self, spec_or_id=None, *args):
48 return thread_execute(self._find_one, spec_or_id, *args)
50 def _insert(self, doc_or_docs, check_keys=True):
54 if isinstance(docs, dict):
61 doc['_id'] = str(ObjectId())
62 if not check_keys or not self._find_one(doc['_id']):
63 ids.append(doc['_id'])
64 self.contents.append(doc_or_docs)
73 def insert(self, doc_or_docs, check_keys=True):
74 return thread_execute(self._insert, doc_or_docs, check_keys)
77 def _compare_date(spec, value):
78 for k, v in spec.iteritems():
79 if k == '$gte' and value >= v:
84 def _in(content, *args):
86 for k, v in arg.iteritems():
88 if not MemDb._compare_date(v, content.get(k)):
90 elif k == 'trust_indicator':
91 if float(content.get(k)) != float(v):
93 elif content.get(k, None) != v:
98 def _find(self, *args):
100 for content in self.contents:
101 if self._in(content, *args):
106 def find(self, *args):
107 return MemCursor(self._find(*args))
109 def _update(self, spec, document):
111 for index in range(len(self.contents)):
112 content = self.contents[index]
113 if self._in(content, spec):
114 for k, v in document.iteritems():
117 self.contents[index] = content
120 def update(self, spec, document):
121 return thread_execute(self._update, spec, document)
123 def _remove(self, spec_or_id=None):
124 if spec_or_id is None:
126 if not isinstance(spec_or_id, dict):
127 spec_or_id = {'_id': spec_or_id}
128 for index in range(len(self.contents)):
129 content = self.contents[index]
130 if self._in(content, spec_or_id):
131 del self.contents[index]
135 def remove(self, spec_or_id=None):
136 return thread_execute(self._remove, spec_or_id)