WebApi: rutas de TEA con figuras del kit
- Dependencia editable indicadores-kit y Python >=3.12 (el kit lo pide).
- Dockerfile copia indicadores_kit/.
- GET /tea/indicadores y GET /tea/indicadores/<id>/figuras/<figura>
(periodos y tema opcionales; 400 y 404 con {"error": ...}).
- GET /tea/pacientes/<int:pac_id>.
- Pruebas de TEA con base temporal por TEA_DATABASE_URL.
This commit is contained in:
+2
-1
@@ -1,5 +1,5 @@
|
||||
# Build context is the ISSSTELEON repo root (see root docker-compose.yml)
|
||||
# so this Dockerfile can COPY its sibling Core/, Persistance/ and models/.
|
||||
# so this Dockerfile can COPY its sibling Core/, Persistance/, models/ and indicadores_kit/.
|
||||
FROM python:3.12-slim
|
||||
|
||||
RUN pip install --no-cache-dir uv
|
||||
@@ -8,6 +8,7 @@ WORKDIR /app
|
||||
COPY Core/ Core/
|
||||
COPY Persistance/ Persistance/
|
||||
COPY models/ models/
|
||||
COPY indicadores_kit/ indicadores_kit/
|
||||
COPY WebApi/ WebApi/
|
||||
|
||||
RUN cd Persistance && uv sync --no-dev
|
||||
|
||||
+3
-1
@@ -2,16 +2,18 @@
|
||||
name = "webapi"
|
||||
version = "0.1.0"
|
||||
description = "Flask REST API fronting Persistance (reads) and models (train/predict) for CaCu, CaMa and TEA."
|
||||
requires-python = ">=3.11"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"flask>=3.0",
|
||||
"persistance",
|
||||
"models",
|
||||
"indicadores-kit",
|
||||
]
|
||||
|
||||
[tool.uv.sources]
|
||||
persistance = { path = "../Persistance", editable = true }
|
||||
models = { path = "../models", editable = true }
|
||||
indicadores-kit = { path = "../indicadores_kit", editable = true }
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import pytest
|
||||
from indicadores_kit.registry.measures import measures_de
|
||||
from indicadores_kit.serving.figuras_tea import FIGURAS_TEA
|
||||
from indicadores_kit.tea import fixtures
|
||||
|
||||
DEFINICIONES = measures_de("tea")
|
||||
PERIODOS = ",".join(fixtures.PERIODOS)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
"""Una base de TEA temporal, con los 18 indicadores calculados, por `TEA_DATABASE_URL`."""
|
||||
# Dentro de la fixture: la configuración de Persistance se lee al importarla,
|
||||
# y test_app.py debe alcanzar a fijar CACU_DATABASE_URL antes.
|
||||
from persistance.db import get_tea_engine
|
||||
from persistance.settings import settings
|
||||
|
||||
ruta = tmp_path_factory.mktemp("tea") / "tea.db"
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(settings, "tea_database_url", f"sqlite:///{ruta}")
|
||||
get_tea_engine.cache_clear()
|
||||
try:
|
||||
fixtures.base_de_prueba(get_tea_engine())
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as cliente:
|
||||
yield cliente
|
||||
finally:
|
||||
get_tea_engine().dispose()
|
||||
get_tea_engine.cache_clear()
|
||||
|
||||
|
||||
def _figura(client, indicador: str, figura: str, query: str = ""):
|
||||
return client.get(f"/tea/indicadores/{indicador}/figuras/{figura}{query}")
|
||||
|
||||
|
||||
def test_listar_indicadores(client):
|
||||
response = client.get("/tea/indicadores")
|
||||
assert response.status_code == 200
|
||||
|
||||
lista = response.get_json()
|
||||
assert [fila["id"] for fila in lista] == sorted(DEFINICIONES)
|
||||
for fila in lista:
|
||||
medida = DEFINICIONES[fila["id"]]
|
||||
assert fila["titulo"] == medida.title
|
||||
assert fila["contrato"] == medida.extension.contrato
|
||||
assert fila["figuras"] == sorted(FIGURAS_TEA[medida.extension.contrato])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_figura_de_cada_indicador(client, indicador):
|
||||
(figura,) = FIGURAS_TEA[DEFINICIONES[indicador].extension.contrato]
|
||||
|
||||
response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.mimetype == "application/json"
|
||||
assert "data" in response.get_json()
|
||||
|
||||
|
||||
def test_figura_sin_periodos_usa_todos_los_reportes(client):
|
||||
(figura,) = FIGURAS_TEA["C1"]
|
||||
|
||||
response = _figura(client, "K01_evaluacion_3_meses", figura)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES["K01_evaluacion_3_meses"].title
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
"?tema=rojo",
|
||||
"?periodos=2025-1",
|
||||
"?periodos=2025-S1,",
|
||||
"?periodos=abc",
|
||||
"?periodos=,",
|
||||
],
|
||||
)
|
||||
def test_figura_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _figura(client, "K01_evaluacion_3_meses", "fig_c1_grupos", query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "figura", "query"),
|
||||
[
|
||||
("K99_no_existe", "fig_c1_grupos", ""),
|
||||
("K01_evaluacion_3_meses", "fig_c2_apiladas", ""), # figura de otro contrato
|
||||
("K01_evaluacion_3_meses", "fig_no_existe", ""),
|
||||
("K01_evaluacion_3_meses", "fig_c1_grupos", "?periodos=2030-S1"), # sin reporte
|
||||
("K01_evaluacion_3_meses", "fig_c1_grupos", f"?periodos={PERIODOS},2030-S2"),
|
||||
],
|
||||
)
|
||||
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
||||
response = _figura(client, indicador, figura, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_paciente_por_id_entero(client):
|
||||
response = client.get("/tea/pacientes/1")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["pac_id_hospital"] == "T-01"
|
||||
|
||||
assert client.get("/tea/pacientes/abc").status_code == 404
|
||||
@@ -1,13 +1,96 @@
|
||||
from flask import Blueprint, jsonify
|
||||
import re
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from indicadores_kit.registry.measures import measures_de
|
||||
from indicadores_kit.serving.figuras_tea import FIGURAS_TEA, TEMAS, figura_json_tea
|
||||
from indicadores_kit.tea.tablas import TABLAS
|
||||
from models.tea import TeaModel
|
||||
from persistance.db import get_tea_session
|
||||
from persistance.tea import pacientes_repository
|
||||
|
||||
tea_bp = Blueprint("tea", __name__)
|
||||
|
||||
# Las 18 definiciones de TEA, por id (nombre del archivo). Son fijas: se leen una vez.
|
||||
DEFINICIONES = measures_de("tea")
|
||||
# Un periodo, como "2025-S1": año y semestre.
|
||||
PERIODO = re.compile(r"\d{4}-S[12]")
|
||||
|
||||
@tea_bp.get("/pacientes/<string:pac_id>")
|
||||
def get_paciente(pac_id: str):
|
||||
|
||||
def _error(mensaje: str, codigo: int):
|
||||
return jsonify({"error": mensaje}), codigo
|
||||
|
||||
|
||||
def _resumen(id_: str, medida) -> dict:
|
||||
contrato = medida.extension.contrato
|
||||
return {
|
||||
"id": id_,
|
||||
"titulo": medida.title,
|
||||
"contrato": contrato,
|
||||
"figuras": sorted(FIGURAS_TEA[contrato]),
|
||||
}
|
||||
|
||||
|
||||
def _periodos_de(texto: str | None) -> list[str]:
|
||||
"""Los periodos de `?periodos=`. Sin parámetro (o vacío), lista vacía: todos los que tienen reporte."""
|
||||
if not texto:
|
||||
return []
|
||||
periodos = texto.split(",")
|
||||
if not all(PERIODO.fullmatch(periodo) for periodo in periodos):
|
||||
raise ValueError(f"Periodos mal formados: {texto!r}; use AAAA-S1 o AAAA-S2.")
|
||||
return list(dict.fromkeys(periodos))
|
||||
|
||||
|
||||
def _periodos_con_reporte(sesion: Session, medida) -> list[str]:
|
||||
reporte = TABLAS.MeasureReport
|
||||
consulta = (
|
||||
select(reporte.periodo_id)
|
||||
.where(reporte.measure_url == medida.url, reporte.measure_version == medida.version)
|
||||
.distinct()
|
||||
.order_by(reporte.periodo_id)
|
||||
)
|
||||
return list(sesion.exec(consulta))
|
||||
|
||||
|
||||
@tea_bp.get("/indicadores")
|
||||
def listar_indicadores():
|
||||
return jsonify([_resumen(id_, medida) for id_, medida in DEFINICIONES.items()])
|
||||
|
||||
|
||||
@tea_bp.get("/indicadores/<indicador>/figuras/<figura>")
|
||||
def get_figura(indicador: str, figura: str):
|
||||
medida = DEFINICIONES.get(indicador)
|
||||
if medida is None:
|
||||
return _error("indicador desconocido", 404)
|
||||
contrato = medida.extension.contrato
|
||||
if figura not in FIGURAS_TEA[contrato]:
|
||||
return _error(f"figura {figura!r} no es del contrato {contrato}", 404)
|
||||
|
||||
tema = request.args.get("tema", "claro")
|
||||
if tema not in TEMAS:
|
||||
return _error(f"tema desconocido {tema!r}; use claro u oscuro", 400)
|
||||
try:
|
||||
periodos = _periodos_de(request.args.get("periodos"))
|
||||
except ValueError as error:
|
||||
return _error(str(error), 400)
|
||||
|
||||
sesion = get_tea_session()
|
||||
try:
|
||||
if not periodos:
|
||||
periodos = _periodos_con_reporte(sesion, medida)
|
||||
if not periodos:
|
||||
return _error("el indicador no tiene reportes calculados", 404)
|
||||
texto = figura_json_tea(sesion, medida, periodos, figura, tablas=TABLAS, tema=tema)
|
||||
except LookupError as error:
|
||||
return _error(str(error), 404)
|
||||
finally:
|
||||
sesion.close()
|
||||
return Response(texto, mimetype="application/json")
|
||||
|
||||
|
||||
@tea_bp.get("/pacientes/<int:pac_id>")
|
||||
def get_paciente(pac_id: int):
|
||||
paciente = pacientes_repository.get(pac_id)
|
||||
if paciente is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
|
||||
Reference in New Issue
Block a user