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
|
import re
from flask import current_app
from bson.objectid import ObjectId
from .db import MongoDB
class UObject(object):
def __init__(self, app=None):
self.app = app
def all(self):
db = MongoDB(self.app)
mongo = db.connection()
return list(mongo.db.uobjects.find({}))
def register(self, datas):
db = MongoDB(self.app)
mongo = db.connection()
if type(datas) != dict:
error = {
"msg": "UObject datas type is not dict (JSON)."
}
return error, 400
_id = mongo.db.uobjects.insert({"datas": datas})
return {"_id": str(_id)}
def remove(self, _id):
db = MongoDB(self.app)
mongo = db.connection()
if not re.match('[0-9a-z]{24}', _id):
error = {
"msg": "UObject _id is must match following regex [0-9a-z]{24}"
}
return error, 400
if len(list(mongo.db.uobjects.find({"_id": ObjectId(_id)}))) == 0:
return '', 404
mongo.db.uobjects.remove({"_id": ObjectId(_id)})
return {"_id": _id}, 200
def update(self, _id, datas):
db = MongoDB(self.app)
mongo = db.connection()
if not _id:
error = {"msg": "UObject _id is required"}
return error, 400
elif len(list(mongo.db.uobjects.find({"_id": ObjectId(_id)}))) == 0:
error = {
"msg": "UObject {} does not exist.".format(_id)
}
return error, 404
datas = dict(
("datas.{}".format(key), value) for (key, value) in datas.items()
)
mongo.db.uobjects.update_one(
{"_id": ObjectId(_id)}, {"$set": datas}
)
return {"msg": "UObject updated.", "_id": _id}
def eq(self, key, value):
db = MongoDB(self.app)
mongo = db.connection()
return list(mongo.db.uobjects.find(
{"datas.{}".format(key): {"$eq": value}}
))
def reset(self):
db = MongoDB(self.app)
mongo = db.connection()
mongo.db.uobjects.remove()
return "done"
|