aboutsummaryrefslogtreecommitdiff
path: root/src/lb_app/app_db/db.py
blob: 005599bf4059a303a4a80c59e40317507f9abf12 (plain)
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
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, 'mongo_db'):
                ctx.mongo_db = self.connect()
            return ctx.mongo_db

    def set_up(self):
        mongo = PyMongo(self.app)
        mongo.cx.drop_database("test_liberationCenter")