32 lines
677 B
Python
32 lines
677 B
Python
from flask import g
|
|
from werkzeug.local import LocalProxy
|
|
from pymongo import MongoClient
|
|
from .config import settings
|
|
|
|
|
|
def connect_db():
|
|
client = MongoClient(settings["mongodb_uri"])
|
|
db = client[settings["mongodb_db"]]
|
|
collection = db[settings["mongodb_collection"]]
|
|
return collection
|
|
|
|
|
|
def disconnect_db(conn):
|
|
conn.database.client.close()
|
|
|
|
|
|
def get_db():
|
|
"""
|
|
Configuration method to return db instance
|
|
"""
|
|
collection = getattr(g, "_database", None)
|
|
|
|
if collection is None:
|
|
collection = g._database = connect_db()
|
|
|
|
return collection
|
|
|
|
|
|
# Use LocalProxy to read the global db instance with just `db`
|
|
db = LocalProxy(get_db)
|