-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmango.py
More file actions
331 lines (276 loc) · 9.08 KB
/
Copy pathmango.py
File metadata and controls
331 lines (276 loc) · 9.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""Mango
A wrapper module that provides simple basic MongoDb operations.
date: 2016-12-19
license: MIT
changes:
2017-09-08
- Changed pattern: modular to object oriented which make available to
connect multiple databases
- Version bumped: 0.2
2016-12-19
- web2py DAL support
- development started
- stable release
- Version bumped: 0.1.7
"""
import collections
import random
import pymongo
from bson.objectid import ObjectId
__version__ = "0.2"
IS_W2P_IMPORT = True
try:
from gluon.contrib.appconfig import AppConfig
except:
IS_W2P_IMPORT = False
def object_id(arg=None):
"""Convert input to a valid Mongodb ObjectId instance.
object_id("<random>") -> ObjectId (not unique) instance
REF: web2py's dal
Args:
arg ([type], optional): Defaults to None. [description]
Raises:
ValueError: Invalid ObjectID argument string
ValueError: Invalid ObjectID. Requires an integer or base 16 value
TypeError: object_id argument must be of type ObjectID or an objectid
representable integer.
Returns:
ObjectId: Mongodb ObjectId
"""
if not arg:
arg = 0
if isinstance(arg, basestring):
# we assume an integer as default input
rawhex = len(arg.replace("0x", "").replace("L", "")) == 24
if arg.isdigit() and (not rawhex):
arg = int(arg)
elif arg == "<random>":
arg = int("0x%s" % "".join([
random.choice("0123456789abcdef")
for x in range(24)]), 0)
elif arg.isalnum():
if not arg.startswith("0x"):
arg = "0x%s" % arg
try:
arg = int(arg, 0)
except ValueError as e:
raise ValueError(
"invalid objectid argument string: %s" % e)
else:
raise ValueError("Invalid objectid argument string. " +
"Requires an integer or base 16 value")
elif isinstance(arg, ObjectId):
return arg
elif not isinstance(arg, (int, long)):
raise TypeError(
"object_id argument must be of type ObjectId or an objectid " +
"representable integer (type %s)" % type(arg))
hexvalue = hex(arg)[2:].rstrip('L').zfill(24)
return ObjectId(hexvalue)
def w2p_id(arg=None, to_str=True):
"""Convert ObjectId to web2py ID.
REF: web2py's dal
Args:
arg ([type], optional): Defaults to None. [description]
to_str (bool, optional): Defaults to True. [description]
Raises:
TypeError: [description]
Returns:
[type]: [description]
"""
if not isinstance(arg, ObjectId):
raise TypeError('w2p_id argument must be ObjectId')
converted = long(str(arg), 16)
if to_str:
return str(converted)
return converted
def to_w2p_id(records, to_web2py_id=False, to_str=True):
"""Convert ObjectId of records to web2py compitible ID.
Args:
records ([type]): [description]
to_web2py_id (bool, optional): Defaults to False. [description]
to_str (bool, optional): Defaults to True. [description]
Returns:
[type]: [description]
"""
mongodb_id_field = '_id'
def converter(row):
if mongodb_id_field in row:
value = row.get(mongodb_id_field)
row['id'] = w2p_id(value, to_str=to_str)
row.pop(mongodb_id_field)
return row
if to_web2py_id:
if isinstance(records, dict):
return converter(records)
elif isinstance(records, collections.Iterable):
return map(converter, records)
return records
def encoding_handler(value, encoding='utf8'):
"""To handle string encoding.
Returns:
[type]: [description]
"""
if isinstance(value, str):
return value.decode(encoding)
elif isinstance(value, unicode):
return value.encode(encoding)
else:
return value
class Mango(object):
"""PyMongo Wrapper: Mango
"""
_uri = None
_client = None
_db = None
_db_name = None
_connected = False
_last_exception = None
def __init__(self, uri=None):
"""Initialize MongoDb Connection using PyMongo.
Args:
uri ([type], optional): Defaults to None. [description]
"""
self._uri = uri
if IS_W2P_IMPORT and not uri:
appconfig = AppConfig()
self._uri = appconfig.get('db.uri')
if self._uri:
self._client = pymongo.MongoClient(self._uri)
self._db = self._client.get_default_database()
self._db_name = self._db.name
def connect(self):
try:
self._client.server_info()
self._connected = True
except pymongo.errors.ServerSelectionTimeoutError as sste:
self._last_exception = sste
self._connected = False
return self._connected
def disconnect(self):
if self._connected:
self._client.close()
def get_table(self, table_name):
"""Get the table object by table_name.
Args:
table_name ([type]): [description]
Returns:
[type]: [description]
"""
return self._db.get_collection(table_name)
def count(self,
table_name,
cond=None,
**kwargs):
"""MongoDb count wrapper function.
Args:
table_name ([type]): [description]
cond ([type], optional): Defaults to None. [description]
Returns:
[type]: [description]
"""
_table = self.get_table(table_name)
return _table.count(cond, **kwargs)
def select(self,
table_name,
cond=None,
is_many=False,
to_web2py_id=False,
**kwargs):
"""MongoDb find wrapper function.
Args:
table_name ([type]): [description]
cond ([type], optional): Defaults to None. [description]
is_many (bool, optional): Defaults to False. [description]
to_web2py_id (bool, optional): Defaults to False. [description]
Returns:
[type]: [description]
"""
_table = self.get_table(table_name)
if not is_many:
return to_w2p_id(
_table.find_one(cond, **kwargs),
to_web2py_id)
else:
return to_w2p_id(
_table.find(cond, **kwargs),
to_web2py_id)
def delete(self,
table_name,
cond=None,
is_many=False,
**kwargs):
"""MongoDb delete wrapper function.
Args:
table_name ([type]): [description]
cond ([type], optional): Defaults to None. [description]
is_many (bool, optional): Defaults to False. [description]
Returns:
[type]: [description]
"""
_table = self.get_table(table_name)
if not is_many:
return _table.delete_one(
cond,
**kwargs)
else:
return _table.delete_many(
cond,
**kwargs)
def update(self,
table_name,
cond=None,
value=None,
is_many=False,
operator="$set",
**kwargs):
"""MongoDb update wrapper function.
Args:
table_name ([type]): [description]
cond ([type], optional): Defaults to None. [description]
value ([type], optional): Defaults to None.
If operator is provided in `value`, `operator` argument will
be ignored.
is_many (bool, optional): Defaults to False. [description]
operator (str, optional): Defaults to "$set". [description]
Returns:
[type]: [description]
"""
_table = self.get_table(table_name)
_update = value
_has_operators = any([k.startswith("$") for k in value.keys()])
if cond and value:
if not _has_operators:
_update = {
operator: value
}
if not is_many:
return _table.update_one(
cond,
_update,
**kwargs)
else:
return _table.update_many(
cond,
_update,
**kwargs)
else:
return None
def insert(self,
table_name,
value=None,
is_many=False,
**kwargs):
"""MongoDb insert wrapper function.
Args:
table_name ([type]): [description]
value ([type], optional): Defaults to None. [description]
is_many (bool, optional): Defaults to False. [description]
Returns:
[type]: [description]
"""
_table = self.get_table(table_name)
if not is_many:
return _table.insert_one(value, **kwargs)
else:
return _table.insert_many(value, **kwargs)