bookmyservice-ams / app /core /database_config.py
MukeshKapoor25's picture
feat: add authentication, security middleware, and optimize JSON handling
fd2ce9d
import os
import motor.motor_asyncio
import redis.asyncio as redis
from redis.exceptions import RedisError
from dotenv import load_dotenv
import logging
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
# Load environment variables from .env file
load_dotenv()
# Load MongoDB configuration
MONGO_URI = os.getenv('MONGO_URI')
DB_NAME = os.getenv('DB_NAME')
CACHE_URI=os.getenv('CACHE_URI')
CACHE_K = os.getenv('CACHE_K')
if not MONGO_URI or not DB_NAME:
raise ValueError("MongoDB URI or Database Name is not set in the environment variables.")
if not CACHE_URI or not CACHE_K:
raise ValueError("Redis URI or Database Name is not set in the environment variables.")
# Parse Redis host and port
CACHE_HOST, CACHE_PORT = CACHE_URI.split(":")
CACHE_PORT = int(CACHE_PORT)
# Initialize MongoDB client
try:
client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_URI)
db = client[DB_NAME]
logger.info(f"Connected to MongoDB database: {DB_NAME}")
except Exception as e:
logger.error(f"Failed to connect to MongoDB: {e}")
raise
# Initialize Redis client
try:
redis_client = redis.Redis(
host=CACHE_HOST,
port=CACHE_PORT,
username="default",
password=CACHE_K,
decode_responses=True
)
logger.info("Connected to Redis.")
except Exception as e:
logger.error(f"Failed to connect to Redis: {e}")
raise