Spaces:
Sleeping
Sleeping
Verbose
Browse files- .env +2 -1
- funciones.py +19 -0
- main.py +23 -0
.env
CHANGED
|
@@ -2,4 +2,5 @@ DB_HOST=opal2.opalstack.com
|
|
| 2 |
DB_USER=moibe
|
| 3 |
mariadb_c=Qaonrr_182
|
| 4 |
DB_NAME=imagen_log
|
| 5 |
-
DB_PORT=3306
|
|
|
|
|
|
| 2 |
DB_USER=moibe
|
| 3 |
mariadb_c=Qaonrr_182
|
| 4 |
DB_NAME=imagen_log
|
| 5 |
+
DB_PORT=3306
|
| 6 |
+
DB_CHARSET=utf8
|
funciones.py
CHANGED
|
@@ -1,9 +1,12 @@
|
|
| 1 |
"""Funciones de lógica de negocio"""
|
| 2 |
|
|
|
|
| 3 |
from datetime import datetime
|
| 4 |
from connection import get_connection
|
| 5 |
from models import RegistroRequest, RegistroResponse
|
| 6 |
|
|
|
|
|
|
|
| 7 |
|
| 8 |
def crear_registro(datos: RegistroRequest) -> dict:
|
| 9 |
"""
|
|
@@ -19,12 +22,14 @@ def crear_registro(datos: RegistroRequest) -> dict:
|
|
| 19 |
conn = get_connection()
|
| 20 |
|
| 21 |
if not conn:
|
|
|
|
| 22 |
return {
|
| 23 |
"success": False,
|
| 24 |
"error": "No se pudo conectar a la base de datos"
|
| 25 |
}
|
| 26 |
|
| 27 |
try:
|
|
|
|
| 28 |
# Preparar datos
|
| 29 |
uid = datos.uid
|
| 30 |
display_name = datos.display_name
|
|
@@ -36,6 +41,8 @@ def crear_registro(datos: RegistroRequest) -> dict:
|
|
| 36 |
proveedor = datos.proveedor
|
| 37 |
seed = datos.seed
|
| 38 |
|
|
|
|
|
|
|
| 39 |
# Insertar en la BD
|
| 40 |
cursor = conn.cursor()
|
| 41 |
|
|
@@ -53,8 +60,11 @@ def crear_registro(datos: RegistroRequest) -> dict:
|
|
| 53 |
cursor.execute(sql, valores)
|
| 54 |
conn.commit()
|
| 55 |
|
|
|
|
|
|
|
| 56 |
# Obtener el ID del registro recién creado
|
| 57 |
nuevo_id = cursor.lastrowid
|
|
|
|
| 58 |
|
| 59 |
# Recuperar el registro creado
|
| 60 |
cursor.execute(
|
|
@@ -72,6 +82,7 @@ def crear_registro(datos: RegistroRequest) -> dict:
|
|
| 72 |
conn.close()
|
| 73 |
|
| 74 |
if registro:
|
|
|
|
| 75 |
return {
|
| 76 |
"success": True,
|
| 77 |
"data": {
|
|
@@ -89,12 +100,14 @@ def crear_registro(datos: RegistroRequest) -> dict:
|
|
| 89 |
}
|
| 90 |
}
|
| 91 |
else:
|
|
|
|
| 92 |
return {
|
| 93 |
"success": False,
|
| 94 |
"error": "No se pudo recuperar el registro creado"
|
| 95 |
}
|
| 96 |
|
| 97 |
except Exception as e:
|
|
|
|
| 98 |
return {
|
| 99 |
"success": False,
|
| 100 |
"error": f"Error al crear registro: {str(e)}"
|
|
@@ -116,17 +129,20 @@ def obtener_registros(limit: int = 10, offset: int = 0) -> dict:
|
|
| 116 |
conn = get_connection()
|
| 117 |
|
| 118 |
if not conn:
|
|
|
|
| 119 |
return {
|
| 120 |
"success": False,
|
| 121 |
"error": "No se pudo conectar a la base de datos"
|
| 122 |
}
|
| 123 |
|
| 124 |
try:
|
|
|
|
| 125 |
cursor = conn.cursor()
|
| 126 |
|
| 127 |
# Obtener total de registros
|
| 128 |
cursor.execute("SELECT COUNT(*) FROM `registro`")
|
| 129 |
total = cursor.fetchone()[0]
|
|
|
|
| 130 |
|
| 131 |
# Obtener registros con paginación
|
| 132 |
cursor.execute(
|
|
@@ -141,6 +157,7 @@ def obtener_registros(limit: int = 10, offset: int = 0) -> dict:
|
|
| 141 |
)
|
| 142 |
|
| 143 |
registros = cursor.fetchall()
|
|
|
|
| 144 |
cursor.close()
|
| 145 |
conn.close()
|
| 146 |
|
|
@@ -161,6 +178,7 @@ def obtener_registros(limit: int = 10, offset: int = 0) -> dict:
|
|
| 161 |
"created_at": reg[10]
|
| 162 |
})
|
| 163 |
|
|
|
|
| 164 |
return {
|
| 165 |
"success": True,
|
| 166 |
"data": datos,
|
|
@@ -170,6 +188,7 @@ def obtener_registros(limit: int = 10, offset: int = 0) -> dict:
|
|
| 170 |
}
|
| 171 |
|
| 172 |
except Exception as e:
|
|
|
|
| 173 |
return {
|
| 174 |
"success": False,
|
| 175 |
"error": f"Error al obtener registros: {str(e)}"
|
|
|
|
| 1 |
"""Funciones de lógica de negocio"""
|
| 2 |
|
| 3 |
+
import logging
|
| 4 |
from datetime import datetime
|
| 5 |
from connection import get_connection
|
| 6 |
from models import RegistroRequest, RegistroResponse
|
| 7 |
|
| 8 |
+
# Configurar logging
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
|
| 11 |
def crear_registro(datos: RegistroRequest) -> dict:
|
| 12 |
"""
|
|
|
|
| 22 |
conn = get_connection()
|
| 23 |
|
| 24 |
if not conn:
|
| 25 |
+
logger.error("❌ No se pudo conectar a la base de datos")
|
| 26 |
return {
|
| 27 |
"success": False,
|
| 28 |
"error": "No se pudo conectar a la base de datos"
|
| 29 |
}
|
| 30 |
|
| 31 |
try:
|
| 32 |
+
logger.info(f"🔗 Conexión establecida a BD")
|
| 33 |
# Preparar datos
|
| 34 |
uid = datos.uid
|
| 35 |
display_name = datos.display_name
|
|
|
|
| 41 |
proveedor = datos.proveedor
|
| 42 |
seed = datos.seed
|
| 43 |
|
| 44 |
+
logger.info(f"📊 Datos a insertar - UID: {uid}, Usuario: {display_name}, País: {pais}, Email: {correo}, Prompt: {prompt}, Proveedor: {proveedor}")
|
| 45 |
+
|
| 46 |
# Insertar en la BD
|
| 47 |
cursor = conn.cursor()
|
| 48 |
|
|
|
|
| 60 |
cursor.execute(sql, valores)
|
| 61 |
conn.commit()
|
| 62 |
|
| 63 |
+
logger.info(f"✅ Registro insertado en BD")
|
| 64 |
+
|
| 65 |
# Obtener el ID del registro recién creado
|
| 66 |
nuevo_id = cursor.lastrowid
|
| 67 |
+
logger.info(f"🔑 ID generado: {nuevo_id}")
|
| 68 |
|
| 69 |
# Recuperar el registro creado
|
| 70 |
cursor.execute(
|
|
|
|
| 82 |
conn.close()
|
| 83 |
|
| 84 |
if registro:
|
| 85 |
+
logger.info(f"✅ Registro recuperado exitosamente - ID: {registro[0]}")
|
| 86 |
return {
|
| 87 |
"success": True,
|
| 88 |
"data": {
|
|
|
|
| 100 |
}
|
| 101 |
}
|
| 102 |
else:
|
| 103 |
+
logger.error("❌ No se pudo recuperar el registro creado")
|
| 104 |
return {
|
| 105 |
"success": False,
|
| 106 |
"error": "No se pudo recuperar el registro creado"
|
| 107 |
}
|
| 108 |
|
| 109 |
except Exception as e:
|
| 110 |
+
logger.error(f"❌ Error al crear registro: {str(e)}")
|
| 111 |
return {
|
| 112 |
"success": False,
|
| 113 |
"error": f"Error al crear registro: {str(e)}"
|
|
|
|
| 129 |
conn = get_connection()
|
| 130 |
|
| 131 |
if not conn:
|
| 132 |
+
logger.error("❌ No se pudo conectar a la base de datos")
|
| 133 |
return {
|
| 134 |
"success": False,
|
| 135 |
"error": "No se pudo conectar a la base de datos"
|
| 136 |
}
|
| 137 |
|
| 138 |
try:
|
| 139 |
+
logger.info(f"🔗 Obteniendo registros - Limit: {limit}, Offset: {offset}")
|
| 140 |
cursor = conn.cursor()
|
| 141 |
|
| 142 |
# Obtener total de registros
|
| 143 |
cursor.execute("SELECT COUNT(*) FROM `registro`")
|
| 144 |
total = cursor.fetchone()[0]
|
| 145 |
+
logger.info(f"📊 Total de registros en BD: {total}")
|
| 146 |
|
| 147 |
# Obtener registros con paginación
|
| 148 |
cursor.execute(
|
|
|
|
| 157 |
)
|
| 158 |
|
| 159 |
registros = cursor.fetchall()
|
| 160 |
+
logger.info(f"✅ Se obtuvieron {len(registros)} registros de la BD")
|
| 161 |
cursor.close()
|
| 162 |
conn.close()
|
| 163 |
|
|
|
|
| 178 |
"created_at": reg[10]
|
| 179 |
})
|
| 180 |
|
| 181 |
+
logger.info(f"📈 Retornando {len(datos)} registros")
|
| 182 |
return {
|
| 183 |
"success": True,
|
| 184 |
"data": datos,
|
|
|
|
| 188 |
}
|
| 189 |
|
| 190 |
except Exception as e:
|
| 191 |
+
logger.error(f"❌ Error al obtener registros: {str(e)}")
|
| 192 |
return {
|
| 193 |
"success": False,
|
| 194 |
"error": f"Error al obtener registros: {str(e)}"
|
main.py
CHANGED
|
@@ -2,12 +2,20 @@
|
|
| 2 |
Aplicación FastAPI - Endpoints
|
| 3 |
"""
|
| 4 |
|
|
|
|
| 5 |
from fastapi import FastAPI, HTTPException, Query
|
| 6 |
from fastapi.responses import JSONResponse
|
| 7 |
from models import RegistroRequest, RegistroResponse
|
| 8 |
from funciones import crear_registro, obtener_registros
|
| 9 |
from datetime import datetime
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
app = FastAPI(
|
| 12 |
title="API Imagen Log",
|
| 13 |
description="API para gestionar registro de usuarios",
|
|
@@ -18,6 +26,7 @@ app = FastAPI(
|
|
| 18 |
@app.get("/", tags=["General"])
|
| 19 |
async def root():
|
| 20 |
"""Endpoint raíz de bienvenida"""
|
|
|
|
| 21 |
return {
|
| 22 |
"mensaje": "Bienvenido a la API de Imagen Log",
|
| 23 |
"version": "1.0.0",
|
|
@@ -28,6 +37,7 @@ async def root():
|
|
| 28 |
@app.get("/health", tags=["General"])
|
| 29 |
async def health():
|
| 30 |
"""Verifica el estado de la API"""
|
|
|
|
| 31 |
return {
|
| 32 |
"status": "healthy",
|
| 33 |
"timestamp": datetime.now().isoformat()
|
|
@@ -55,15 +65,19 @@ async def registrar(datos: RegistroRequest):
|
|
| 55 |
**Respuesta:** Retorna los datos del registro creado con su ID único
|
| 56 |
"""
|
| 57 |
|
|
|
|
|
|
|
| 58 |
resultado = crear_registro(datos)
|
| 59 |
|
| 60 |
if resultado["success"]:
|
|
|
|
| 61 |
return {
|
| 62 |
"success": True,
|
| 63 |
"message": "Registro creado exitosamente",
|
| 64 |
"data": resultado["data"]
|
| 65 |
}
|
| 66 |
else:
|
|
|
|
| 67 |
raise HTTPException(
|
| 68 |
status_code=400,
|
| 69 |
detail=resultado["error"]
|
|
@@ -85,9 +99,12 @@ async def obtener_todos_registros(
|
|
| 85 |
**Respuesta:** Lista de registros con información de paginación
|
| 86 |
"""
|
| 87 |
|
|
|
|
|
|
|
| 88 |
resultado = obtener_registros(limit, offset)
|
| 89 |
|
| 90 |
if resultado["success"]:
|
|
|
|
| 91 |
return {
|
| 92 |
"success": True,
|
| 93 |
"data": resultado["data"],
|
|
@@ -99,6 +116,7 @@ async def obtener_todos_registros(
|
|
| 99 |
}
|
| 100 |
}
|
| 101 |
else:
|
|
|
|
| 102 |
raise HTTPException(
|
| 103 |
status_code=500,
|
| 104 |
detail=resultado["error"]
|
|
@@ -108,3 +126,8 @@ async def obtener_todos_registros(
|
|
| 108 |
if __name__ == "__main__":
|
| 109 |
import uvicorn
|
| 110 |
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
Aplicación FastAPI - Endpoints
|
| 3 |
"""
|
| 4 |
|
| 5 |
+
import logging
|
| 6 |
from fastapi import FastAPI, HTTPException, Query
|
| 7 |
from fastapi.responses import JSONResponse
|
| 8 |
from models import RegistroRequest, RegistroResponse
|
| 9 |
from funciones import crear_registro, obtener_registros
|
| 10 |
from datetime import datetime
|
| 11 |
|
| 12 |
+
# Configurar logging
|
| 13 |
+
logging.basicConfig(
|
| 14 |
+
level=logging.INFO,
|
| 15 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 16 |
+
)
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
app = FastAPI(
|
| 20 |
title="API Imagen Log",
|
| 21 |
description="API para gestionar registro de usuarios",
|
|
|
|
| 26 |
@app.get("/", tags=["General"])
|
| 27 |
async def root():
|
| 28 |
"""Endpoint raíz de bienvenida"""
|
| 29 |
+
logger.info("📍 Llamado a endpoint raíz /")
|
| 30 |
return {
|
| 31 |
"mensaje": "Bienvenido a la API de Imagen Log",
|
| 32 |
"version": "1.0.0",
|
|
|
|
| 37 |
@app.get("/health", tags=["General"])
|
| 38 |
async def health():
|
| 39 |
"""Verifica el estado de la API"""
|
| 40 |
+
logger.info("✅ Health check")
|
| 41 |
return {
|
| 42 |
"status": "healthy",
|
| 43 |
"timestamp": datetime.now().isoformat()
|
|
|
|
| 65 |
**Respuesta:** Retorna los datos del registro creado con su ID único
|
| 66 |
"""
|
| 67 |
|
| 68 |
+
logger.info(f"📝 Nuevo registro - UID: {datos.uid}, Email: {datos.correo}, Prompt: {datos.prompt}")
|
| 69 |
+
|
| 70 |
resultado = crear_registro(datos)
|
| 71 |
|
| 72 |
if resultado["success"]:
|
| 73 |
+
logger.info(f"✅ Registro creado exitosamente - ID: {resultado['data']['id']}, UID: {datos.uid}")
|
| 74 |
return {
|
| 75 |
"success": True,
|
| 76 |
"message": "Registro creado exitosamente",
|
| 77 |
"data": resultado["data"]
|
| 78 |
}
|
| 79 |
else:
|
| 80 |
+
logger.error(f"❌ Error al crear registro: {resultado['error']}")
|
| 81 |
raise HTTPException(
|
| 82 |
status_code=400,
|
| 83 |
detail=resultado["error"]
|
|
|
|
| 99 |
**Respuesta:** Lista de registros con información de paginación
|
| 100 |
"""
|
| 101 |
|
| 102 |
+
logger.info(f"📚 Obteniendo registros - Limit: {limit}, Offset: {offset}")
|
| 103 |
+
|
| 104 |
resultado = obtener_registros(limit, offset)
|
| 105 |
|
| 106 |
if resultado["success"]:
|
| 107 |
+
logger.info(f"✅ Se obtuvieron {len(resultado['data'])} registros (Total: {resultado['total']})")
|
| 108 |
return {
|
| 109 |
"success": True,
|
| 110 |
"data": resultado["data"],
|
|
|
|
| 116 |
}
|
| 117 |
}
|
| 118 |
else:
|
| 119 |
+
logger.error(f"❌ Error al obtener registros: {resultado['error']}")
|
| 120 |
raise HTTPException(
|
| 121 |
status_code=500,
|
| 122 |
detail=resultado["error"]
|
|
|
|
| 126 |
if __name__ == "__main__":
|
| 127 |
import uvicorn
|
| 128 |
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
import uvicorn
|
| 133 |
+
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|