1 ##############################################################################
2 # Copyright (c) 2016 ZTE Corporation
3 # feng.xiaowei@zte.com.cn
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9 from bson.objectid import ObjectId
10 from concurrent.futures import ThreadPoolExecutor
13 def thread_execute(method, *args, **kwargs):
14 with ThreadPoolExecutor(max_workers=2) as executor:
15 result = executor.submit(method, *args, **kwargs)
19 class MemCursor(object):
20 def __init__(self, collection):
21 self.collection = collection
22 self.count = len(self.collection)
24 def _is_next_exist(self):
25 return self.count != 0
29 return thread_execute(self._is_next_exist)
31 def next_object(self):
33 return self.collection.pop()
42 def _find_one(self, spec_or_id=None, *args):
43 if spec_or_id is not None and not isinstance(spec_or_id, dict):
44 spec_or_id = {"_id": spec_or_id}
45 if '_id' in spec_or_id:
46 spec_or_id['_id'] = str(spec_or_id['_id'])
47 cursor = self._find(spec_or_id, *args)
52 def find_one(self, spec_or_id=None, *args):
53 return thread_execute(self._find_one, spec_or_id, *args)
55 def _insert(self, doc_or_docs, check_keys=True):
59 if isinstance(docs, dict):
66 doc['_id'] = str(ObjectId())
67 if not check_keys or not self._find_one(doc['_id']):
68 ids.append(doc['_id'])
69 self.contents.append(doc_or_docs)
78 def insert(self, doc_or_docs, check_keys=True):
79 return thread_execute(self._insert, doc_or_docs, check_keys)
82 def _compare_date(spec, value):
83 for k, v in spec.iteritems():
84 if k == '$gte' and value >= v:
89 def _in(content, *args):
91 for k, v in arg.iteritems():
93 if not MemDb._compare_date(v, content.get(k)):
95 elif k == 'trust_indicator':
96 if float(content.get(k)) != float(v):
98 elif content.get(k, None) != v:
103 def _find(self, *args):
105 for content in self.contents:
106 if self._in(content, *args):
111 def find(self, *args):
112 return MemCursor(self._find(*args))
114 def _update(self, spec, document):
116 for index in range(len(self.contents)):
117 content = self.contents[index]
118 if self._in(content, spec):
119 for k, v in document.iteritems():
122 self.contents[index] = content
125 def update(self, spec, document):
126 return thread_execute(self._update, spec, document)
128 def _remove(self, spec_or_id=None):
129 if spec_or_id is None:
131 if not isinstance(spec_or_id, dict):
132 spec_or_id = {'_id': spec_or_id}
133 for index in range(len(self.contents)):
134 content = self.contents[index]
135 if self._in(content, spec_or_id):
136 del self.contents[index]
140 def remove(self, spec_or_id=None):
141 return thread_execute(self._remove, spec_or_id)