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 # Variables globales para Cosmos DB MongoDB API mongo_client = None mongo_db = None def initialize_cosmos_sql_connection(): global cosmos_client, user_database, user_container, application_requests_container, user_feedback_container try: 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 and COSMOS_KEY environment variables must be set") cosmos_client = CosmosClient(cosmos_endpoint, cosmos_key) user_database = cosmos_client.get_database_client("user_database") user_container = user_database.get_container_client("users") application_requests_container = user_database.get_container_client("application_requests") user_feedback_container = user_database.get_container_client("user_feedback") 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)}", exc_info=True) return False def initialize_mongodb_connection(): global mongo_client, mongo_db try: cosmos_mongodb_connection_string = os.getenv("MONGODB_CONNECTION_STRING") if not cosmos_mongodb_connection_string: raise ValueError("MONGODB_CONNECTION_STRING environment variable is not set") mongo_client = MongoClient(cosmos_mongodb_connection_string, tls=True, tlsCAFile=certifi.where(), retryWrites=False, serverSelectionTimeoutMS=5000, connectTimeoutMS=10000, socketTimeoutMS=10000) mongo_client.admin.command('ping') mongo_db = mongo_client['aideatext_db'] logger.info("Conexión a Cosmos DB MongoDB API exitosa") return True except Exception as e: logger.error(f"Error al conectar con Cosmos DB MongoDB API: {str(e)}", exc_info=True) return False def initialize_database_connections(): sql_success = initialize_cosmos_sql_connection() mongodb_success = initialize_mongodb_connection() return sql_success and mongodb_success def get_sql_containers(): if user_container is None or application_requests_container is None or user_feedback_container is None: initialize_cosmos_sql_connection() return user_container, application_requests_container, user_feedback_container def get_mongodb(): if mongo_db is None: initialize_mongodb_connection() return mongo_db