Use source patient identity for breast follow-up

This commit is contained in:
Angel Capetillo Zavala
2026-11-13 17:38:19 -06:00
parent 2ca86232c9
commit eeb55c4255
11 changed files with 73 additions and 110 deletions
+6 -23
View File
@@ -99,26 +99,9 @@ se omiten.
### Seguimiento CaMa sintético
`GET /cama/seguimiento` entrega la tabla declarativa de demostración, sin consultar una base. Por defecto usa corte fijo `2026-10-20`, ventana de 3 meses, página 1 y tamaño 50. `corte` acepta fecha ISO; `meses` admite 1, 3, 6 o 12; `page` comienza en 1 y `page_size` va de 1 a 200. La ventana incluye desde el día siguiente a restar meses calendario (ajustando fin de mes) hasta el corte inclusive. Se seleccionan filas por fecha de mastografía. No se acota un corte solicitado a la última fecha del fixture.
Los filtros opcionales son `estatus` (`PENDIENTE_BIOPSIA`, `BIOPSIA_SIN_RESULTADO`, `CANCER_CONFIRMADO`, `BENIGNO`, `INFO_INSUFICIENTE`), `birads` (`BIRADS_4A`, `BIRADS_4B`, `BIRADS_4C`, `BIRADS_5`, `BIRADS_6`), `grupo_edad` (`40-49`, `50-59`, `60-69`, `70+`) y `prioridad` (`ALTA`, `MEDIA`, `BAJA`). `filtros_disponibles` anuncia códigos y etiquetas; las celdas incluyen etiquetas y campos `*_codigo`. Se ordena por fecha descendente e ID ascendente, antes de paginar. Una página fuera de rango devuelve 200 con `items: []`; una lista vacía tiene cero páginas. Parámetros inválidos producen 400 y un fallo de lectura 500 con JSON `error`.
#### Contratos candidatos F5B
`GET /cama/seguimiento/exportacion?corte=2026-10-20&meses=1&birads=BIRADS_5` devuelve todas las coincidencias, con los mismos filtros y orden de la lista. El cuerpo incluye `simulado`, `corte`, `ventana`, `campo_ventana`, `filtros`, `filtros_disponibles`, `columnas`, `total_items` e `items`. Ejemplo abreviado (los arreglos de metadatos se omiten aquí, pero siempre se envían):
```json
{"simulado":true,"corte":"2026-10-20","ventana":{"meses":1,"desde":"2026-09-21","hasta":"2026-10-20"},"campo_ventana":"mastografia_fecha","filtros":{"estatus":null,"birads":"BIRADS_5","grupo_edad":null,"prioridad":null},"total_items":1,"items":[{"id_seudonimo":"M-0001","mastografia_fecha":"2026-10-15","estatus":"Pendiente de biopsia","estatus_codigo":"PENDIENTE_BIOPSIA","birads":"BI-RADS 5","birads_codigo":"BIRADS_5","grupo_edad":"50-59","grupo_edad_codigo":"50-59","prioridad":"Alta","prioridad_codigo":"ALTA","biopsia":null,"biopsia_fecha":null,"dias_mastografia_diagnostico":null}]}
```
Más de 5,000 coincidencias produce 413 con `error`, sin truncar. No requiere parámetros de paginación; si se envían, se validan como en la lista pero no limitan el resultado. JSON vacío es 200 con `total_items: 0` e `items: []`. Las respuestas, incluidos errores, llevan `Cache-Control: no-store`.
`GET /cama/pacientes/M-0001?corte=2026-10-20&meses=1` devuelve `{"simulado":true,"corte":"2026-10-20","ventana":{"meses":1,"desde":"2026-09-21","hasta":"2026-10-20"},"item":{...}}`, donde `item` es exactamente la fila anterior. Deben enviarse el corte y la ventana de la lista; un ID inexistente o fuera de esa ventana devuelve 404. Solo existen los campos de la fila: historial, pronóstico y demás apartados no disponibles se omiten; los campos existentes sin datos son `null`. También utiliza `no-store`. Los ID `M-...` pertenecen exclusivamente al fixture y no son `pac_id`.
#### Ruta futura a persistencia
La conexión CaMa se configura mediante `CAMA_DATABASE_URL` en `Persistance/persistance/settings.py` y `db.py`; el valor por defecto es `sqlite:///cama.db`, mientras `.env.example` propone otra ruta. Esto no identifica el motor instalado en DEV. En staging, `Paciente`, `Mastografia`, `BiopsiaMama` y `OrdenesEstudio` están en `Core/core/cama/models`; la plata expone `Persona`, `Procedimiento` y `Observacion` mediante `indicadores_kit/cama/tablas.py`. `indicadores_kit/cama/plata.py` transforma tomas, reportes y observaciones; no asumir que `cama_linea_de_tiempo` está disponible en una instalación sin comprobarlo.
Antes de consultar persistencia hay que validar identidad entre `pac_id` y `pac_id_hospital`, claves opcionales, la relación `biopsiamama.mast_id`, órdenes, múltiples estudios/resultados, fechas de toma y reporte, y selección de eventos conocidos al corte. La biopsia sin fecha de reporte no aporta aún resultado en el patrón de plata. El servicio `seguimiento_de` de CaCu ilustra sesión externa, reglas parametrizadas, agrupación por paciente, ventana, orden y seudonimización; sus reglas clínicas no deben copiarse como reglas CaMa. Un identificador opaco estable con clave secreta y separación por dominio, por ejemplo HMAC, requiere acordar gestión y rotación de clave, colisiones y resolución autorizada para detalle; no exponer `str(pac_id)` directamente.
Angular hoy exige `simulado === true` en `SeguimientoTablaService`. Una fuente real requiere acordar el contrato y tratamiento de `simulado: false`, adaptar tipos, validación, etiquetas, pruebas y acceso antes de consumirla. No se ha cambiado el proveedor ni se ha verificado el despliegue remoto.
El lector usa la base configurada por `CAMA_DATABASE_URL` y publica el
`pac_id` de la plataforma como cadena decimal, con ámbito limitado a esa base
y dominio. El acceso a las rutas por paciente requiere el token configurado en
el servidor. Los parámetros de corte, ventana y selección, la revisión, la
supresión y los ejemplos de listado, ficha y exportación se describen en
[el contrato de cohorte](docs/cama-cohort-api.md).
+9 -12
View File
@@ -1,12 +1,9 @@
# Breast cohort: synthetic integration contract
This contract is opt-in and only for a synthetic source. Set
`CAMA_COHORT_SYNTHETIC=1`, `CAMA_COHORT_SECRET` and
`CAMA_COHORT_ACCESS_TOKEN` in the server environment. The pseudonym secret
must have at least 32 UTF-8 bytes; the token must be at least 32 ASCII
This contract is for a synthetic source. Set `CAMA_COHORT_ACCESS_TOKEN` in
the server environment. The token must be at least 32 ASCII
letters, digits, underscores or hyphens. The application reads the configured CaMa database
and checks the `X-Cama-Cohort-Token` request header on patient routes. Store
the pseudonym secret persistently: changing it changes every pseudonym. The
and checks the `X-Cama-Cohort-Token` request header on patient routes. The
header must be supplied by a trusted server-side access boundary, never
embedded in browser code. Without an enabled reader the aggregate returns
503; without authorized access the patient routes return 403. This is not a
@@ -24,7 +21,7 @@ No survival, recurrence, subgroup grid or other analysis endpoints are supplied.
One patient contributes once: choose the latest mammogram with a BI-RADS report
available by cutoff; then include it if BI-RADS is 4, 4A, 4B, 4C, 5 or 6.
`revision` is a digest of the materialized cohort, including its data and stable
pseudonyms. It is an integrity marker, not an authorization credential.
patient identifiers. It is an integrity marker, not an authorization credential.
For each patient request send `cohorte=cama_birads_v1`, `escenario=diagnostico`,
the exact `revision` and `corte` from the aggregate, `meses`, and any selected
@@ -35,7 +32,7 @@ GET /cama/seguimiento?cohorte=cama_birads_v1&escenario=diagnostico&revision=<rev
```
For the same selected population use the same query on
`/cama/seguimiento/exportacion` or `/cama/pacientes/<id_seudonimo>`; list
`/cama/seguimiento/exportacion` or `/cama/pacientes/<pac_id>`; list
accepts `page` and `page_size` (maximum 200). Export is limited to 5,000.
`meses=0` means the whole eligible cohort through cutoff. Its inclusive
`desde` is the earliest eligible mammography date before filtering; when the
@@ -72,13 +69,13 @@ materializes the full cohort in memory and has not been sized for production.
The local example `examples/serve_cama_cohort.py` accepts an existing synthetic
SQLite file in `CAMA_SYNTHETIC_SQLITE`, opens it read-only, binds to loopback,
and requires `CAMA_COHORT_SECRET` and `CAMA_COHORT_ACCESS_TOKEN` of at least
32 characters. Send the latter in `X-Cama-Cohort-Token` for patient requests.
and requires `CAMA_COHORT_ACCESS_TOKEN` of at least 32 characters. Send it in
`X-Cama-Cohort-Token` for patient requests.
Other domain database URLs are set to isolated in-memory SQLite by the example.
The Windows-only `fcntl` shim raises if locking is attempted: this example does
not validate file-locking functionality.
`examples/serve_cama_integration.py` runs normal application configuration
against an existing disposable SQLite copy, with a stable secret file and a
temporary token injected by its loopback-only test proxy. It is suitable only
against an existing disposable SQLite copy, with a temporary token injected by
its loopback-only test proxy. It is suitable only
for local synthetic integration and does not provide production authentication.
+3 -4
View File
@@ -24,10 +24,9 @@ if os.name == 'nt':
path = Path(os.environ['CAMA_SYNTHETIC_SQLITE']).resolve(strict=True)
secret = os.environ['CAMA_COHORT_SECRET'].encode()
token = os.environ['CAMA_COHORT_ACCESS_TOKEN']
if len(secret) < 32 or len(token) < 32:
raise ValueError('Both the cohort secret and access token must be at least 32 characters')
if len(token) < 32:
raise ValueError('The access token must be at least 32 characters')
if not path.is_file():
raise ValueError('The synthetic SQLite database must already exist')
@@ -47,7 +46,7 @@ app = create_app()
def read(cutoff):
with Session(engine) as session:
return CamaCohort(session, secret).rows(cutoff)
return CamaCohort(session).rows(cutoff)
def authorized(request):
-7
View File
@@ -9,20 +9,13 @@ import types
parser = argparse.ArgumentParser()
parser.add_argument('--database', required=True, help='Existing disposable synthetic SQLite database')
parser.add_argument('--secret-file', required=True, help='Persistent local pseudonym secret file')
parser.add_argument('--port', type=int, default=5059)
args = parser.parse_args()
database = Path(args.database).resolve(strict=True)
if not database.is_file():
raise ValueError('The synthetic database must be an existing file')
secret_file = Path(args.secret_file).resolve()
if not secret_file.exists():
with secret_file.open('x', encoding='ascii') as output:
output.write(secrets.token_hex(32))
secret = secret_file.read_text(encoding='ascii').strip()
token = secrets.token_hex(32)
os.environ.update(CAMA_DATABASE_URL='sqlite:///' + database.as_posix(),
CAMA_COHORT_SYNTHETIC='1', CAMA_COHORT_SECRET=secret,
CAMA_COHORT_ACCESS_TOKEN=token, MLFLOW_DISABLE_AGENT_HINT='1',
MLFLOW_DISABLE_TELEMETRY='true')
for domain in ('CACU', 'TEA', 'GOVERNANCE'):
+12 -13
View File
@@ -57,7 +57,7 @@ def client(cohort_db):
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix='/cama')
def read(cutoff):
with Session(cohort_db) as session:
return CamaCohort(session, b'x' * 32).rows(cutoff)
return CamaCohort(session).rows(cutoff)
app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=lambda req: True)
return app.test_client()
@@ -84,7 +84,7 @@ def test_aggregate_list_detail_and_export_have_one_selection(client):
exported = client.get('/cama/seguimiento/exportacion' + selection).get_json()
assert exported['items'] == items and exported['total_items'] == 6
for item in items:
detail = client.get('/cama/pacientes/' + item['id_seudonimo'] + selection).get_json()
detail = client.get('/cama/pacientes/' + item['pac_id'] + selection).get_json()
assert detail['item'] == item and detail['corte'] == aggregate['corte']
assert sum(item['biopsia'] == 'BENIGNO' for item in items) == 1
assert client.get('/cama/seguimiento' + selection).get_json()['items'] == items
@@ -115,16 +115,15 @@ def test_cutoff_excludes_later_clinical_and_load_dates(client):
def test_links_and_load_dates_are_distinct(client, cohort_db):
"""A missing link and a late load cannot supply a diagnosis before cutoff."""
with Session(cohort_db) as session:
ids = {i: CamaCohort(session, b'x' * 32)._id(i) for i in range(1, 5)}
ids = {i: str(i) for i in range(1, 5)}
data = client.get('/cama/seguimiento' + query(client)).get_json()
rows = {item['id_seudonimo']: item for item in data['items']}
rows = {item['pac_id']: item for item in data['items']}
assert rows[ids[1]]['biopsia'] == 'BENIGNO'
assert rows[ids[2]]['biopsia'] is None and rows[ids[2]]['biopsia_fecha'] is None
assert rows[ids[3]]['biopsia'] is None and rows[ids[3]]['biopsia_fecha'] == '2025-02-15'
assert rows[ids[4]]['biopsia'] is None and rows[ids[4]]['biopsia_fecha'] is None
later = client.get('/cama/seguimiento' + query(client, '2027-12-01')).get_json()
rows_later = {item['id_seudonimo']: item for item in later['items']}
rows_later = {item['pac_id']: item for item in later['items']}
assert rows_later[ids[3]]['biopsia'] == 'BENIGNO'
assert rows_later[ids[4]]['biopsia_fecha'] == '2027-02-15'
assert set(rows) == set(rows_later)
@@ -143,11 +142,11 @@ def test_full_application_registers_cohort_and_regular_followup(client):
def test_windows_and_disabled_provider(client):
"""Regular windows remain available and the reader is opt-in."""
"""Regular windows remain available and a missing reader returns unavailable."""
selection = query(client).replace('&meses=0', '&meses=1').replace('&birads=BIRADS_5', '')
body = client.get('/cama/seguimiento' + selection).get_json()
assert body['items'] == [] and body['ventana']['desde'] == '2026-09-21'
client.application.config['CAMA_COHORT_SYNTHETIC'] = False
client.application.config['CAMA_COHORT_READER'] = None
assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503
@@ -178,8 +177,8 @@ def test_cross_patient_links_and_observations_are_not_used(cohort_db):
# The BI-RADS observation belongs to a different patient.
session.get(TABLAS.Observacion, 6).pac_id = 5
session.commit()
reader = CamaCohort(session, b'x' * 32)
rows = {row['id_seudonimo']: row for row in reader.rows(date(2027, 12, 1))}
assert reader._id(6) not in rows
assert rows[reader._id(1)]['biopsia'] is None
assert rows[reader._id(3)]['biopsia'] is None
reader = CamaCohort(session)
rows = {row['pac_id']: row for row in reader.rows(date(2027, 12, 1))}
assert '6' not in rows
assert rows['1']['biopsia'] is None
assert rows['3']['biopsia'] is None
+9 -21
View File
@@ -1,38 +1,26 @@
"""Verify the synthetic cohort's opt-in startup and server-side access check."""
"""Exercise persistent cohort setup and its optional patient access boundary."""
import pytest
from flask import Flask
from flask import Flask, request
from webapi.cama_runtime import configure_cama_cohort
def test_synthetic_cohort_requires_explicit_configuration(monkeypatch):
"""Missing or short secrets must not silently enable patient access."""
monkeypatch.delenv('CAMA_COHORT_SYNTHETIC', raising=False)
def test_missing_or_invalid_token_does_not_prevent_startup(monkeypatch):
"""A malformed optional credential leaves the reader registered and access denied."""
monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 'short')
app = Flask(__name__)
configure_cama_cohort(app)
assert 'CAMA_COHORT_READER' not in app.config
monkeypatch.setenv('CAMA_COHORT_SYNTHETIC', '1')
monkeypatch.setenv('CAMA_COHORT_SECRET', 'short')
monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 't' * 32)
with pytest.raises(ValueError):
configure_cama_cohort(app)
monkeypatch.setenv('CAMA_COHORT_SECRET', 's' * 32)
monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 't' * 32 + '";')
with pytest.raises(ValueError):
configure_cama_cohort(app)
assert callable(app.config['CAMA_COHORT_READER'])
with app.test_request_context(headers={'X-Cama-Cohort-Token': 'short'}):
assert not app.config['CAMA_COHORT_ACCESS'](request)
def test_access_token_is_checked_on_the_server(monkeypatch):
"""Only requests bearing the configured token can use the cohort patient routes."""
monkeypatch.setenv('CAMA_COHORT_SYNTHETIC', '1')
monkeypatch.setenv('CAMA_COHORT_SECRET', 's' * 32)
"""The retained proxy credential gates patient routes until a shared boundary is available."""
monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 't' * 32)
app = Flask(__name__)
configure_cama_cohort(app)
with app.test_request_context(headers={'X-Cama-Cohort-Token': 't' * 32}):
from flask import request
assert app.config['CAMA_COHORT_ACCESS'](request)
with app.test_request_context(headers={'X-Cama-Cohort-Token': 'incorrect'}):
from flask import request
assert not app.config['CAMA_COHORT_ACCESS'](request)
+15 -3
View File
@@ -12,7 +12,7 @@ from webapi.seguimiento_cama import blueprint_seguimiento_cama
@pytest.fixture
def client():
"""A fixed six-person cohort and a server-controlled access callback."""
rows = [dict(id_seudonimo=f'patient-{n}', mastografia_fecha='2026-10-15',
rows = [dict(pac_id=str(n + 1), mastografia_fecha='2026-10-15',
birads='BIRADS_5', grupo_edad='50-59', biopsia=None,
biopsia_fecha=None) for n in range(6)]
app = Flask(__name__)
@@ -36,7 +36,7 @@ def test_regular_list_detail_and_export_use_the_same_selection(client):
rows.extend(client.get('/cama/seguimiento' + query + context + f'&page_size=2&page={number}', headers=headers).get_json()['items'])
exported = client.get('/cama/seguimiento/exportacion' + query + context, headers=headers).get_json()
assert exported['items'] == rows
assert client.get('/cama/pacientes/' + rows[0]['id_seudonimo'] + query + context, headers=headers).get_json()['item'] == rows[0]
assert client.get('/cama/pacientes/' + rows[0]['pac_id'] + query + context, headers=headers).get_json()['item'] == rows[0]
assert client.get('/cama/seguimiento' + query, headers=headers).headers['Cache-Control'] == 'no-store'
@@ -54,5 +54,17 @@ def test_disabled_provider_and_empty_window(client):
headers = {'X-Test': 'yes'}
body = client.get('/cama/seguimiento?corte=2025-01-01&meses=3', headers=headers).get_json()
assert body['items'] == [] and body['paginacion']['total_items'] == 0
client.application.config['CAMA_COHORT_SYNTHETIC'] = False
client.application.config['CAMA_COHORT_READER'] = None
assert client.get('/cama/seguimiento', headers=headers).status_code == 503
def test_provider_failure_does_not_break_other_routes(client):
"""A failing cohort source returns unavailable while the app can serve other requests."""
def fail(_cutoff):
raise RuntimeError('provider unavailable')
client.application.add_url_rule('/health', 'health', lambda: {'status': 'ok'})
client.application.config['CAMA_COHORT_READER'] = fail
assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503
assert client.get('/cama/seguimiento?corte=2026-10-20', headers={'X-Test': 'yes'}).status_code == 503
assert client.get('/health').get_json() == {'status': 'ok'}
+8 -4
View File
@@ -21,9 +21,13 @@ class SelectionError(Exception):
def read_cohort(cutoff):
reader = current_app.config.get('CAMA_COHORT_READER')
if current_app.config.get('CAMA_COHORT_SYNTHETIC') is not True or not callable(reader):
if not callable(reader):
raise SelectionError('Cohorte no disponible', 503)
return reader(cutoff)
try:
return reader(cutoff)
except Exception:
current_app.logger.exception('Breast cohort provider failed')
raise SelectionError('Cohorte no disponible', 503) from None
def cutoff_arg(args):
@@ -115,7 +119,7 @@ def selection_response(args, mode, patient=None):
cutoff, months, page, size, filters, since, rows, revision = selected(args)
options = [('birads', 'Categoría BI-RADS', BIRADS), ('grupo_edad', 'Grupo de edad', AGES)]
columns = [
{'clave': 'id_seudonimo', 'etiqueta': 'Identificador seudónimo'},
{'clave': 'pac_id', 'etiqueta': 'Identificador de paciente'},
{'clave': 'grupo_edad', 'etiqueta': 'Grupo de edad'},
{'clave': 'birads', 'etiqueta': 'Última mastografía', 'detalles': [{'clave': 'mastografia_fecha', 'etiqueta': 'Fecha'}]},
{'clave': 'biopsia', 'etiqueta': 'Resultado histopatológico', 'detalles': [{'clave': 'biopsia_fecha', 'etiqueta': 'Fecha de reporte'}]},
@@ -126,7 +130,7 @@ def selection_response(args, mode, patient=None):
'filtros_disponibles': [{'clave': k, 'etiqueta': label, 'opciones': [{'codigo': v, 'etiqueta': v} for v in values]}
for k, label, values in options], 'columnas': columns}
if mode == 'patient':
found = next((row for row in rows if row['id_seudonimo'] == patient), None)
found = next((row for row in rows if row['pac_id'] == patient), None)
if found is None:
raise SelectionError('Paciente no encontrado', 404)
return jsonify(**meta, item=found)
+3 -11
View File
@@ -6,8 +6,6 @@ restore a previous value after an update.
"""
from datetime import date, datetime, time, timedelta, timezone
import hashlib
import hmac
from sqlalchemy import select
@@ -49,14 +47,8 @@ def _age_group(birth, cutoff):
class CamaCohort:
"""Materialize one row per eligible patient, using a caller-owned session."""
def __init__(self, session, secret: bytes):
if not secret or len(secret) < 32:
raise ValueError("A stable secret of at least 32 bytes is required")
def __init__(self, session):
self.session = session
self.secret = secret
def _id(self, patient):
return hmac.new(self.secret, f"cama:{patient}".encode(), hashlib.sha256).hexdigest()
def rows(self, cutoff: date):
t = TABLAS
@@ -128,7 +120,7 @@ class CamaCohort:
order = found_order[1] if found_order and _date(found_order[1].fecha) >= _date(m['fecha_toma']) else None
grade = b['grado'] if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None
rows.append({
'id_seudonimo': self._id(patient), 'mastografia_fecha': _date(m['fecha_toma']).isoformat(),
'pac_id': str(patient), 'mastografia_fecha': _date(m['fecha_toma']).isoformat(),
'mastografia_reporte_fecha': _date(m['fecha_reporte']).isoformat(),
'birads': code, 'grupo_edad': _age_group(people[patient].fecha_nacimiento, cutoff),
'biopsia': grade, 'biopsia_fecha': _date(b['fecha_reporte']).isoformat() if b else None,
@@ -141,4 +133,4 @@ class CamaCohort:
'biopsia_resultado_carga_inicio': load_time(observations.get((b['procedimiento_id'], 'biopsia.grado')))
if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None,
})
return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), row['id_seudonimo']))
return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), int(row['pac_id'])))
+5 -9
View File
@@ -1,4 +1,4 @@
"""Configure the opt-in synthetic breast cohort for the application."""
"""Configure the breast cohort using the shared persistence settings."""
import hmac
import os
@@ -9,19 +9,15 @@ from webapi.cama_cohort import CamaCohort
def configure_cama_cohort(app):
if os.environ.get('CAMA_COHORT_SYNTHETIC') != '1':
return
secret = os.environ.get('CAMA_COHORT_SECRET', '').encode('utf-8')
token = os.environ.get('CAMA_COHORT_ACCESS_TOKEN', '')
if len(secret) < 32 or not re.fullmatch(r'[A-Za-z0-9_-]{32,}', token):
raise ValueError('Synthetic cohort requires a stable secret and a URL-safe access token of at least 32 characters')
def read(cutoff):
with get_cama_session() as session:
return CamaCohort(session, secret).rows(cutoff)
return CamaCohort(session).rows(cutoff)
def access(req):
supplied = req.headers.get('X-Cama-Cohort-Token', '')
return hmac.compare_digest(supplied.encode('utf-8'), token.encode('utf-8'))
return bool(re.fullmatch(r'[A-Za-z0-9_-]{32,}', token)) and hmac.compare_digest(
supplied.encode('utf-8'), token.encode('utf-8'))
app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=access)
app.config.update(CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=access)
+3 -3
View File
@@ -39,8 +39,8 @@ def blueprint_seguimiento_cama():
def exportacion():
return respond('export')
@blueprint.get("/pacientes/<id_seudonimo>")
def paciente(id_seudonimo):
return respond('patient', id_seudonimo)
@blueprint.get("/pacientes/<pac_id>")
def paciente(pac_id):
return respond('patient', pac_id)
return blueprint