diff options
Diffstat (limited to 'umosapi/app_db')
-rw-r--r-- | umosapi/app_db/__init__.py | 0 | ||||
-rw-r--r-- | umosapi/app_db/db.py | 31 | ||||
-rw-r--r-- | umosapi/app_db/uobject.py | 48 |
3 files changed, 79 insertions, 0 deletions
diff --git a/umosapi/app_db/__init__.py b/umosapi/app_db/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/umosapi/app_db/__init__.py diff --git a/umosapi/app_db/db.py b/umosapi/app_db/db.py new file mode 100644 index 0000000..70b8f7c --- /dev/null +++ b/umosapi/app_db/db.py @@ -0,0 +1,31 @@ +from flask import current_app, _app_ctx_stack +from flask_pymongo import PyMongo + + +class MongoDB(object): + def __init__(self, app=None): + self.app = app + if app is not None: + self.init_app(app) + + def init_app(self, app): + app.teardown_appcontext(self.teardown) + + def connect(self): + return PyMongo(self.app, current_app.config['MONGO_URI']) + + def teardown(self, exception): + ctx = _app_ctx_stack.top + if hasattr(ctx, 'mongo_db'): + ctx.mongo_db.cx.close() + + def connection(self): + ctx = _app_ctx_stack.top + if ctx is not None: + if not hasattr(ctx, 'mongodb'): + ctx.mongo_db = self.connect() + return ctx.mongo_db + + def set_up(self): + mongo = PyMongo(self.app) + mongo.cx.drop_database("umosapi") diff --git a/umosapi/app_db/uobject.py b/umosapi/app_db/uobject.py new file mode 100644 index 0000000..175ac52 --- /dev/null +++ b/umosapi/app_db/uobject.py @@ -0,0 +1,48 @@ +from flask import current_app + +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.objects.find({})) + + def register(self, name): + db = MongoDB(self.app) + mongo = db.connection() + error = {} + + if not name: + error = {'msg': 'Object name is required.', 'code': 400} + elif len(list(mongo.db.objects.find({"name": name}))) > 0: + error = { + 'msg': 'Object {} is already registered.'.format(name), + 'code': 409 + } + if not error: + mongo.db.objects.insert({"name": name}) + return {'msg': 'Object {} added.'.format(name), 'code': 201} + return error + + def remove(self, name): + db = MongoDB(self.app) + mongo = db.connection() + error = {} + + if not name: + error = {'msg': 'Object name is required', 'code': 400} + elif len(list(mongo.db.objects.find({"name": name}))) == 0: + error = { + 'msg': "User {} not exist. So it's good".format(name), + 'code': 404 + } + + if not error: + mongo.db.objects.remove({'name': name}) + return {'msg': 'Object {} deleted'.format(name), 'code': 200} + return error |