Files
softone_zadanie/app/db.py
2023-09-28 17:08:50 +02:00

38 lines
947 B
Python

from flask import g
from pymongo import MongoClient
from .config import settings
def connect_db():
"""
Creates the connection to the MongoDB using the config file data.
Thos function is used by flask application as well as the scraper script
:return: connection to the collection in the mongodb
"""
client = MongoClient(settings["mongodb_uri"])
db = client[settings["mongodb_db"]]
collection = db[settings["mongodb_collection"]]
return collection
def disconnect_db(conn):
"""
Disconnects open connection
:param conn: open db connection
"""
conn.database.client.close()
def get_db():
"""
Get collection instance for flask application. If no instance stored in global variables, then create connection
and store it in g
"""
collection = getattr(g, "_database", None)
if collection is None:
collection = g._database = connect_db()
return collection