Files

114 lines
5.0 KiB
Python

"""The routes of CaMa's follow-up list: `GET /cama/seguimiento` and `GET /cama/seguimiento/exportacion`."""
import json
import re
from collections.abc import Callable
from datetime import date
from flask import Blueprint, Response, current_app, jsonify, request
from sqlmodel import Session
from webapi.cama_follow_up.cohort import CohorteNoDisponible
from webapi.cama_follow_up.access import configured_access
from webapi.cama_follow_up.listing import (
ExportacionGrande, GrupoPequeno, PaginaFuera, PedidoInvalido, RevisionDistinta, exportacion_de, seguimiento_de, paciente_de,
)
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
FILTROS = ("birads", "grupo_edad", "biopsia", "escenario_clinico")
CONTEXTO = ("cohorte", "escenario", "revision")
ENTEROS = ("meses", "page", "page_size")
def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
"""The blueprint of the list and its file, to register with `url_prefix="/cama"`."""
blueprint = Blueprint("cama_seguimiento", __name__)
blueprint.before_request(configured_access)
@blueprint.after_request
def no_store(response):
response.headers["Cache-Control"] = "no-store"
return response
def answer(build, admitidos: tuple[str, ...], legacy_mode=None, patient=None):
reader = current_app.config.get('CAMA_COHORT_READER')
if legacy_mode and 'CAMA_COHORT_READER' in current_app.config and not getattr(reader, '_cama_default_reader', False):
from webapi.cama_analysis_legacy import SelectionError, selection_response
try:
return selection_response(request.args, legacy_mode, patient)
except SelectionError as error:
return jsonify(error=error.message), error.status
try:
pedido = _requested(request.args, admitidos)
except ValueError as error:
return jsonify({"error": str(error)}), 400
sesion = get_session()
try:
cuerpo = build(sesion, **pedido)
except PedidoInvalido as error:
return jsonify({"error": str(error)}), 400
except GrupoPequeno as error:
return jsonify({"error": str(error), "motivo": "supresion"}), 403
except PaginaFuera as error:
return jsonify({"error": str(error)}), 404
except RevisionDistinta as error:
return jsonify({"error": str(error), "motivo": "revision"}), 409
except ExportacionGrande as error:
return jsonify({"error": str(error)}), 413
except CohorteNoDisponible as error:
return jsonify({"error": str(error), "motivo": "cohorte"}), 503
finally:
sesion.close()
return Response(json.dumps(cuerpo, ensure_ascii=False), mimetype="application/json")
@blueprint.get("/seguimiento")
def get_seguimiento():
"""The BI-RADS cohort's follow-up list at a cut-off, one page."""
return answer(seguimiento_de, ("corte", *ENTEROS, *CONTEXTO, *FILTROS), 'list')
@blueprint.get("/seguimiento/exportacion")
def get_exportacion():
"""Every row of the same selection, for a file."""
return answer(exportacion_de, ("corte", "meses", *CONTEXTO, *FILTROS), 'export')
@blueprint.get('/pacientes/<pac_id>')
def paciente(pac_id):
return answer(lambda session, **pedido: paciente_de(session, pac_id, **pedido),
('corte', *ENTEROS, *CONTEXTO, *FILTROS), 'patient', pac_id)
return blueprint
def _requested(args, admitidos: tuple[str, ...]) -> dict:
"""The query's parameters, typed. `ValueError` for an unknown, repeated or badly written one."""
for nombre in args:
if nombre not in admitidos:
raise ValueError(f"parámetro desconocido {nombre!r}; se admite {list(admitidos)}.")
if len(args.getlist(nombre)) > 1:
raise ValueError(f"parámetro repetido {nombre!r}.")
pedido: dict = {}
if (corte := args.get("corte")) is not None:
if not FECHA.fullmatch(corte):
raise ValueError(f"corte mal escrito {corte!r}; use AAAA-MM-DD")
try:
pedido["corte"] = date.fromisoformat(corte)
except ValueError:
raise ValueError(f"corte {corte!r} no es una fecha") from None
for nombre in ENTEROS:
if nombre in args:
if not re.fullmatch(r"\d{1,6}", args[nombre]):
raise ValueError(f"{nombre} debe ser un entero; llegó {args[nombre]!r}")
pedido[nombre] = int(args[nombre])
contexto = {n: args[n] for n in CONTEXTO if n in args}
if contexto and len(contexto) != len(CONTEXTO):
raise ValueError(f"el contexto de la cohorte lleva {list(CONTEXTO)} juntos.")
if any(not v for v in contexto.values()):
raise ValueError("el contexto de la cohorte no puede ir vacío.")
pedido.update(contexto)
filtros = {n: args[n] for n in FILTROS if n in args}
if any(not v for v in filtros.values()):
raise ValueError("un filtro no puede ir vacío.")
if filtros:
pedido["filtros"] = filtros
return pedido