Update modules/database/database_init.py
Browse files
modules/database/database_init.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
|
2 |
|
3 |
import os
|
4 |
import logging
|
@@ -15,7 +15,7 @@ user_database = None
|
|
15 |
user_container = None
|
16 |
application_requests_container = None
|
17 |
user_feedback_container = None
|
18 |
-
user_sessions_container = None
|
19 |
|
20 |
# Variables globales para Cosmos DB MongoDB API
|
21 |
mongo_client = None
|
@@ -26,20 +26,32 @@ def verify_container_partition_key(container, expected_path):
|
|
26 |
try:
|
27 |
container_props = container.read()
|
28 |
partition_key_paths = container_props['partitionKey']['paths']
|
29 |
-
|
30 |
logger.info(f"Container: {container.id}, Partition Key Paths: {partition_key_paths}")
|
31 |
-
|
32 |
-
if expected_path not in partition_key_paths:
|
33 |
-
logger.warning(
|
34 |
-
f"Partition key incorrecta en {container.id}. "
|
35 |
-
f"Actual: {partition_key_paths}, Esperada: {expected_path}"
|
36 |
-
)
|
37 |
-
return False
|
38 |
-
return True
|
39 |
except Exception as e:
|
40 |
logger.error(f"Error verificando partition key en {container.id}: {str(e)}")
|
41 |
return False
|
42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
def initialize_cosmos_sql_connection():
|
44 |
"""Inicializa y verifica la conexi贸n a Cosmos DB SQL API"""
|
45 |
global cosmos_client, user_database, user_container, \
|
@@ -53,11 +65,10 @@ def initialize_cosmos_sql_connection():
|
|
53 |
if not cosmos_endpoint or not cosmos_key:
|
54 |
raise ValueError("COSMOS_ENDPOINT and COSMOS_KEY environment variables must be set")
|
55 |
|
56 |
-
# Inicializar cliente y obtener contenedores
|
57 |
cosmos_client = CosmosClient(cosmos_endpoint, cosmos_key)
|
58 |
user_database = cosmos_client.get_database_client("user_database")
|
59 |
|
60 |
-
# Configuraci贸n de contenedores
|
61 |
containers_config = {
|
62 |
"users": ("/id", user_container),
|
63 |
"application_requests": ("/email", application_requests_container),
|
@@ -65,28 +76,21 @@ def initialize_cosmos_sql_connection():
|
|
65 |
"users_sessions": ("/username", user_sessions_container)
|
66 |
}
|
67 |
|
68 |
-
# Inicializar
|
69 |
for container_id, (expected_path, container_ref) in containers_config.items():
|
70 |
container = user_database.get_container_client(container_id)
|
71 |
if not verify_container_partition_key(container, expected_path):
|
72 |
logger.error(f"Verificaci贸n de partition key fall贸 para {container_id}")
|
73 |
return False
|
74 |
|
75 |
-
# Actualizar
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
application_requests_container = container
|
80 |
-
elif container_id == "user_feedback":
|
81 |
-
user_feedback_container = container
|
82 |
-
elif container_id == "users_sessions":
|
83 |
-
user_sessions_container = container
|
84 |
-
|
85 |
-
logger.info("Conexi贸n a Cosmos DB SQL API exitosa y particiones verificadas")
|
86 |
return True
|
87 |
|
88 |
except Exception as e:
|
89 |
-
logger.error(f"Error al conectar con Cosmos DB SQL API: {str(e)}"
|
90 |
return False
|
91 |
|
92 |
def initialize_mongodb_connection():
|
@@ -107,39 +111,21 @@ def initialize_mongodb_connection():
|
|
107 |
socketTimeoutMS=10000
|
108 |
)
|
109 |
|
110 |
-
# Verificar conexi贸n
|
111 |
mongo_client.admin.command('ping')
|
112 |
mongo_db = mongo_client['aideatext_db']
|
113 |
-
|
114 |
logger.info("Conexi贸n a Cosmos DB MongoDB API exitosa")
|
115 |
return True
|
116 |
|
117 |
except Exception as e:
|
118 |
-
logger.error(f"Error al conectar con Cosmos DB MongoDB API: {str(e)}"
|
119 |
return False
|
120 |
|
121 |
def initialize_database_connections():
|
122 |
"""Inicializa todas las conexiones a bases de datos"""
|
123 |
-
|
124 |
-
mongodb_success = initialize_mongodb_connection()
|
125 |
-
|
126 |
-
if sql_success and mongodb_success:
|
127 |
-
logger.info("Todas las conexiones a bases de datos inicializadas correctamente")
|
128 |
-
else:
|
129 |
-
logger.error("Fall贸 la inicializaci贸n de una o m谩s conexiones a bases de datos")
|
130 |
-
|
131 |
-
return sql_success and mongodb_success
|
132 |
-
|
133 |
-
def get_sql_containers():
|
134 |
-
"""Obtiene los contenedores SQL, reinicializando si es necesario"""
|
135 |
-
if any(container is None for container in
|
136 |
-
[user_container, application_requests_container,
|
137 |
-
user_feedback_container, user_sessions_container]):
|
138 |
-
initialize_cosmos_sql_connection()
|
139 |
-
return user_container, application_requests_container, user_feedback_container, user_sessions_container
|
140 |
|
141 |
def get_mongodb():
|
142 |
-
"""Obtiene la conexi贸n MongoDB
|
143 |
if mongo_db is None:
|
144 |
initialize_mongodb_connection()
|
145 |
return mongo_db
|
|
|
1 |
+
# 1. modules/database/database_init.py
|
2 |
|
3 |
import os
|
4 |
import logging
|
|
|
15 |
user_container = None
|
16 |
application_requests_container = None
|
17 |
user_feedback_container = None
|
18 |
+
user_sessions_container = None
|
19 |
|
20 |
# Variables globales para Cosmos DB MongoDB API
|
21 |
mongo_client = None
|
|
|
26 |
try:
|
27 |
container_props = container.read()
|
28 |
partition_key_paths = container_props['partitionKey']['paths']
|
|
|
29 |
logger.info(f"Container: {container.id}, Partition Key Paths: {partition_key_paths}")
|
30 |
+
return expected_path in partition_key_paths
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
except Exception as e:
|
32 |
logger.error(f"Error verificando partition key en {container.id}: {str(e)}")
|
33 |
return False
|
34 |
|
35 |
+
def get_container(container_name):
|
36 |
+
"""Obtiene un contenedor espec铆fico"""
|
37 |
+
containers = {
|
38 |
+
"users": (user_container, "/id"),
|
39 |
+
"application_requests": (application_requests_container, "/email"),
|
40 |
+
"user_feedback": (user_feedback_container, "/username"),
|
41 |
+
"users_sessions": (user_sessions_container, "/username")
|
42 |
+
}
|
43 |
+
|
44 |
+
if container_name not in containers:
|
45 |
+
logger.error(f"Contenedor no v谩lido: {container_name}")
|
46 |
+
return None
|
47 |
+
|
48 |
+
container, partition_path = containers[container_name]
|
49 |
+
if container is None:
|
50 |
+
initialize_cosmos_sql_connection()
|
51 |
+
container, _ = containers[container_name]
|
52 |
+
|
53 |
+
return container
|
54 |
+
|
55 |
def initialize_cosmos_sql_connection():
|
56 |
"""Inicializa y verifica la conexi贸n a Cosmos DB SQL API"""
|
57 |
global cosmos_client, user_database, user_container, \
|
|
|
65 |
if not cosmos_endpoint or not cosmos_key:
|
66 |
raise ValueError("COSMOS_ENDPOINT and COSMOS_KEY environment variables must be set")
|
67 |
|
|
|
68 |
cosmos_client = CosmosClient(cosmos_endpoint, cosmos_key)
|
69 |
user_database = cosmos_client.get_database_client("user_database")
|
70 |
|
71 |
+
# Configuraci贸n de contenedores
|
72 |
containers_config = {
|
73 |
"users": ("/id", user_container),
|
74 |
"application_requests": ("/email", application_requests_container),
|
|
|
76 |
"users_sessions": ("/username", user_sessions_container)
|
77 |
}
|
78 |
|
79 |
+
# Inicializar contenedores
|
80 |
for container_id, (expected_path, container_ref) in containers_config.items():
|
81 |
container = user_database.get_container_client(container_id)
|
82 |
if not verify_container_partition_key(container, expected_path):
|
83 |
logger.error(f"Verificaci贸n de partition key fall贸 para {container_id}")
|
84 |
return False
|
85 |
|
86 |
+
# Actualizar referencia global
|
87 |
+
globals()[f"{container_id}_container"] = container
|
88 |
+
|
89 |
+
logger.info("Conexi贸n a Cosmos DB SQL API exitosa")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
return True
|
91 |
|
92 |
except Exception as e:
|
93 |
+
logger.error(f"Error al conectar con Cosmos DB SQL API: {str(e)}")
|
94 |
return False
|
95 |
|
96 |
def initialize_mongodb_connection():
|
|
|
111 |
socketTimeoutMS=10000
|
112 |
)
|
113 |
|
|
|
114 |
mongo_client.admin.command('ping')
|
115 |
mongo_db = mongo_client['aideatext_db']
|
|
|
116 |
logger.info("Conexi贸n a Cosmos DB MongoDB API exitosa")
|
117 |
return True
|
118 |
|
119 |
except Exception as e:
|
120 |
+
logger.error(f"Error al conectar con Cosmos DB MongoDB API: {str(e)}")
|
121 |
return False
|
122 |
|
123 |
def initialize_database_connections():
|
124 |
"""Inicializa todas las conexiones a bases de datos"""
|
125 |
+
return initialize_cosmos_sql_connection() and initialize_mongodb_connection()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
126 |
|
127 |
def get_mongodb():
|
128 |
+
"""Obtiene la conexi贸n MongoDB"""
|
129 |
if mongo_db is None:
|
130 |
initialize_mongodb_connection()
|
131 |
return mongo_db
|