import os from urllib.parse import quote_plus from flask import current_app, g from pymongo import MongoClient from dotenv import load_dotenv load_dotenv() def get_db(): """ Configuration method to return db instance """ if 'db' not in g: # These should ideally be loaded from app.config mongodb_user = os.getenv('MONGODB_USER_LIVE') mongodb_password = quote_plus(os.getenv('MONGODB_PASSWORD_LIVE')) mongodb_host = os.getenv('MONGODB_HOST_LIVE') # Use the correct HOST variable mongodb_port = os.getenv('MONGODB_PORT_LIVE', 27017) # Default to 27017 if not set mongodb_db_name = os.environ.get('MONGODB_DB_LIVE') # The client is stored in the application context to be reused across requests in the same worker. if 'mongo_client' not in current_app.config: current_app.config['mongo_client'] = MongoClient(f"mongodb://{mongodb_user}:{mongodb_password}@{mongodb_host}:{mongodb_port}/") g.db = current_app.config['mongo_client'][mongodb_db_name] return g.db