forked from ayaankazerouni/flask-playground-db-access
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel_mongodb.py
50 lines (42 loc) · 1.32 KB
/
model_mongodb.py
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
import pymongo
from bson import ObjectId
class Model(dict):
"""
A simple model that wraps mongodb document
"""
__getattr__ = dict.get
__delattr__ = dict.__delitem__
__setattr__ = dict.__setitem__
def save(self):
if not self._id:
self.collection.insert(self)
else:
self.collection.update(
{ "_id": ObjectId(self._id) }, self)
self._id = str(self._id)
def reload(self):
if self._id:
result = self.collection.find_one({"_id": ObjectId(self._id)})
if result :
self.update(result)
self._id = str(self._id)
return True
return False
def remove(self):
if self._id:
resp = self.collection.remove({"_id": ObjectId(self._id)})
self.clear()
return resp
class User(Model):
db_client = pymongo.MongoClient('localhost', 27017)
collection = db_client["users"]["users_list"]
def find_all(self):
users = list(self.collection.find())
for user in users:
user["_id"] = str(user["_id"])
return users
def find_by_name(self, name):
users = list(self.collection.find({"name": name}))
for user in users:
user["_id"] = str(user["_id"])
return users