Files
WebApi/webapi/__init__.py
T

134 lines
5.8 KiB
Python

import datetime as _dt
import logging
import os
from decimal import Decimal
from flask import Flask, jsonify
from flask.json.provider import DefaultJSONProvider
from webapi.blueprints.cacu import cacu_bp
from webapi.blueprints.data import data_bp
from webapi.blueprints.governance import governance_bp
from webapi.blueprints.imports import imports_bp
from webapi.blueprints.reports import reports_bp
from webapi.cama_analysis.routes import analysis_blueprint as cama_analysis_blueprint
from webapi.cama_follow_up.routes import follow_up_blueprint as cama_follow_up_blueprint
from webapi.cama_recurrence.routes import cama_recurrence_bp
from webapi.follow_up.routes import follow_up_blueprint
class IsoJSONProvider(DefaultJSONProvider):
"""ISO-8601 dates (Flask's default is RFC 822); files are never sent
inline in JSON, only their size."""
@staticmethod
def default(o):
if isinstance(o, (_dt.datetime, _dt.date, _dt.time)):
return o.isoformat()
if isinstance(o, Decimal):
return float(o)
if isinstance(o, (bytes, bytearray)):
return f"<{len(o)} bytes>"
return DefaultJSONProvider.default(o)
def create_app() -> Flask:
app = Flask(__name__)
app.json = IsoJSONProvider(app)
from webapi.cama_runtime import configure_cama_cohort
configure_cama_cohort(app)
# File sources travel inside the request; cap them per request.
app.config["MAX_CONTENT_LENGTH"] = int(os.environ.get("WEBAPI_MAX_UPLOAD_MB", "200")) * 1024 * 1024
# The web client goes through a proxy; browser clients on other origins
# are allowed with WEBAPI_CORS_ORIGINS (comma-separated).
cors_origins = os.environ.get("WEBAPI_CORS_ORIGINS")
if cors_origins:
from flask_cors import CORS
CORS(app, origins=[origin.strip() for origin in cors_origins.split(",")])
@app.get("/health")
def health():
return {"status": "ok"}
@app.get("/api")
def api_index():
"""Every route with its methods and summary, for programmatic clients."""
routes = []
for rule in sorted(app.url_map.iter_rules(), key=lambda r: r.rule):
if rule.endpoint == "static":
continue
doc = (app.view_functions[rule.endpoint].__doc__ or "").strip()
routes.append(
{
"path": rule.rule,
"methods": sorted(rule.methods - {"HEAD", "OPTIONS"}),
"summary": " ".join(doc.split("\n\n")[0].split()),
}
)
return jsonify({"routes": routes})
@app.errorhandler(413)
def too_large(_exc):
limit_mb = app.config["MAX_CONTENT_LENGTH"] // (1024 * 1024)
return jsonify({"error": f"la solicitud excede {limit_mb} MB"}), 413
app.register_blueprint(cacu_bp, url_prefix="/cacu")
app.register_blueprint(imports_bp, url_prefix="/imports")
app.register_blueprint(data_bp, url_prefix="/data")
app.register_blueprint(governance_bp, url_prefix="/governance")
app.register_blueprint(reports_bp, url_prefix="/reportes")
# The measures, answered on request from dbt's semantic definitions: the deployment ships their manifest.
if os.environ.get("DBT_MANIFEST"):
from importlib import import_module
from pathlib import Path
from webapi.fhir import fhir_blueprint
from webapi.kpis import kpis_blueprint
for domain in ("cacu", "cama", "tea"):
repositories, manifest = import_module(f"persistance.{domain}"), Path(os.environ["DBT_MANIFEST"])
app.register_blueprint(kpis_blueprint(domain, repositories, manifest), url_prefix=f"/{domain}")
# The same measures in FHIR R4, with TEA's patient summary (simulated data, marked in every response).
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=True),
url_prefix=f"/{domain}/fhir")
# Patient-level follow-up list, marked `simulado` in every response (a CaCu patient's individual risk is FHIR's
# `RiskAssessment`, under `/cacu/fhir`). Who may see them is an access rule still to be defined.
from persistance import cacu as cacu_repositories
from persistance import cama as cama_repositories
from persistance.db import get_cacu_session, get_cama_session
from webapi.model_analysis import model_analysis_blueprint, recurrence_blueprint
from webapi.risk_batches import risk_batches_blueprint
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
app.register_blueprint(cama_recurrence_bp, url_prefix="/cama/recurrencia")
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
app.register_blueprint(risk_batches_blueprint(cama_repositories, "risk_batches_cama"), url_prefix="/cama")
app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama")
app.register_blueprint(recurrence_blueprint(), url_prefix="/cama")
if os.environ.get("WEBAPI_PRECALENTAR_MODELOS") == "1":
_warm_in_background()
return app
def _warm_in_background() -> None:
"""Loads the live models' members in each worker as it starts, so the first patient opened doesn't wait for them."""
import threading
from webapi.model_analysis import LIVE_SCENARIOS, warm
def run():
for domain in LIVE_SCENARIOS:
try:
warm(domain)
except Exception: # the request that needs them will try again and say why
logging.getLogger(__name__).exception("no se pudieron precargar los modelos de %s", domain)
threading.Thread(target=run, name="precarga-modelos", daemon=True).start()