File size: 4,131 Bytes
5a585eb 29ca692 3d560cd 5a585eb 3d560cd da81392 3d560cd 5a585eb 3d560cd da81392 5a585eb da81392 220a9a0 da81392 220a9a0 5a585eb da81392 3d560cd da81392 3d560cd da81392 220a9a0 3d560cd da81392 3d560cd da81392 5a585eb 3d560cd 5a585eb 3d560cd da81392 3d560cd da81392 3d560cd da81392 3d560cd da81392 3d560cd da81392 3d560cd da81392 3d560cd da81392 5a585eb 3d560cd da81392 3d560cd 5a585eb 3d560cd c58df45 |
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
# 1. modules/database/database_init.py
import os
import logging
from azure.cosmos import CosmosClient
from pymongo import MongoClient
import certifi
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Variables globales para Cosmos DB SQL API
cosmos_client = None
user_database = None
user_container = None
application_requests_container = None
user_feedback_container = None
user_sessions_container = None
# Variables globales para Cosmos DB MongoDB API
mongo_client = None
mongo_db = None
###################################################################
def verify_container_partition_key(container, expected_path):
"""Verifica la configuraci贸n de partition key de un contenedor"""
try:
container_props = container.read()
partition_key_paths = container_props['partitionKey']['paths']
logger.info(f"Container: {container.id}, Partition Key Paths: {partition_key_paths}")
return expected_path in partition_key_paths
except Exception as e:
logger.error(f"Error verificando partition key en {container.id}: {str(e)}")
return False
###################################################################
def get_container(container_name):
"""Obtiene un contenedor espec铆fico"""
global user_container, user_sessions_container
if not initialize_cosmos_sql_connection():
logger.error("No se pudo inicializar la conexi贸n")
return None
containers = {
"users": user_container,
"users_sessions": user_sessions_container
}
return containers.get(container_name)
###################################################################
def initialize_cosmos_sql_connection():
"""Inicializa la conexi贸n a Cosmos DB SQL API"""
global cosmos_client, user_database, user_container, user_sessions_container
try:
if cosmos_client and user_database and user_container and user_sessions_container:
return True
cosmos_endpoint = os.environ.get("COSMOS_ENDPOINT")
cosmos_key = os.environ.get("COSMOS_KEY")
if not cosmos_endpoint or not cosmos_key:
raise ValueError("COSMOS_ENDPOINT y COSMOS_KEY deben estar configurados")
cosmos_client = CosmosClient(cosmos_endpoint, cosmos_key)
user_database = cosmos_client.get_database_client("user_database")
# Inicializar contenedores manteniendo la estructura existente
user_container = user_database.get_container_client("users")
user_sessions_container = user_database.get_container_client("users_sessions")
logger.info("Conexi贸n a Cosmos DB SQL API exitosa")
return True
except Exception as e:
logger.error(f"Error al conectar con Cosmos DB SQL API: {str(e)}")
return False
###################################################################
def initialize_mongodb_connection():
"""Inicializa la conexi贸n a MongoDB"""
global mongo_client, mongo_db
try:
connection_string = os.getenv("MONGODB_CONNECTION_STRING")
if not connection_string:
raise ValueError("MONGODB_CONNECTION_STRING debe estar configurado")
mongo_client = MongoClient(
connection_string,
tls=True,
tlsCAFile=certifi.where(),
retryWrites=False,
serverSelectionTimeoutMS=5000,
connectTimeoutMS=10000,
socketTimeoutMS=10000
)
mongo_db = mongo_client['aideatext_db']
return True
except Exception as e:
logger.error(f"Error conectando a MongoDB: {str(e)}")
return False
###################################################################
def initialize_database_connections():
"""Inicializa todas las conexiones"""
return initialize_cosmos_sql_connection() and initialize_mongodb_connection()
###################################################################
def get_mongodb():
"""Obtiene la conexi贸n MongoDB"""
if mongo_db is None:
initialize_mongodb_connection()
return mongo_db |