Files
WebApi/webapi/fhir/common.py

118 lines
5.0 KiB
Python

"""What every FHIR R4 answer of the WebApi shares: the media type, errors as `OperationOutcome`, search bundles with
their paging links, the simulated-data tag and the project's canonical URLs. Every answer is validated against FHIR's
R4B models (`fhir.resources`, the models the EEG analysis validates its own report with) before it leaves."""
import json
import logging
import os
from urllib.parse import urlencode
from flask import Response, request
FHIR_VERSION = "4.0.1"
MEDIA_TYPE = "application/fhir+json"
BASE = "https://isssteleon.org/fhir"
CODE_SYSTEM = f"{BASE}/CodeSystem"
VALUE_SET = f"{BASE}/ValueSet"
STRUCTURE = f"{BASE}/StructureDefinition"
SIMULATED = {"system": f"{CODE_SYSTEM}/etiqueta", "code": "simulado", "display": "Datos simulados"}
MAX_COUNT = 200
DEFAULT_COUNT = 50
log = logging.getLogger(__name__)
def validated(resource: dict) -> dict:
"""The resource as FHIR's R4B models read it and write it back (R4B keeps R4's shape for these resources).
`ValueError` if it doesn't conform."""
from fhir.resources.R4B import get_fhir_model_class
try:
model = get_fhir_model_class(resource["resourceType"])
except KeyError as exc:
raise ValueError(f"no FHIR resource type {resource.get('resourceType')!r}") from exc
return model.model_validate(resource).model_dump(mode="json", exclude_none=True)
def fhir(resource: dict, status: int = 200) -> Response:
"""A resource as the answer, in FHIR's JSON media type. One that doesn't conform to FHIR never leaves: the answer
is then a 500 `OperationOutcome`, and the reason goes to the log."""
try:
body = validated(resource)
except ValueError:
if resource.get("resourceType") == "OperationOutcome":
raise
log.exception("a %s answer doesn't conform to FHIR R4B", resource.get("resourceType"))
return outcome(500, "exception", "la respuesta no es un recurso FHIR válido")
return Response(json.dumps(body, ensure_ascii=False), status=status, mimetype=MEDIA_TYPE)
def outcome(status: int, code: str, diagnostics: str, severity: str = "error") -> Response:
"""An error as an `OperationOutcome` (`code` from FHIR's issue-type), with the HTTP status it goes with."""
return fhir({"resourceType": "OperationOutcome",
"issue": [{"severity": severity, "code": code, "diagnostics": diagnostics}]}, status)
def canonical(path: str) -> str:
"""The absolute canonical of a project resource: `Measure/<id>`, `CodeSystem/<id>`…"""
return f"{BASE}/{path}"
def coding(system: str, code: str, display: str | None = None) -> dict:
return {"system": system, "code": code, **({"display": display} if display else {})}
def concept(system: str, code: str, display: str | None = None, text: str | None = None) -> dict:
return {"coding": [coding(system, code, display)], **({"text": text} if text else {})}
def tagged(resource: dict, simulated: bool) -> dict:
"""The resource with the simulated-data tag in its `meta`, when its data are simulated."""
if simulated:
resource.setdefault("meta", {}).setdefault("tag", []).append(SIMULATED)
return resource
def simulated_data() -> bool:
"""Patient data are simulated in the DEV deployment (`DEV_REVISION`), the only one that serves them."""
return bool(os.environ.get("DEV_REVISION"))
def page() -> tuple[int, int]:
"""`_count` (at most `MAX_COUNT`) and `_offset` of the search. `ValueError` if one isn't a number."""
count = int(request.args.get("_count", DEFAULT_COUNT))
offset = int(request.args.get("_offset", 0))
if count < 0 or offset < 0:
raise ValueError("`_count` y `_offset` no pueden ser negativos")
return min(count, MAX_COUNT), offset
def searchset(entries: list[dict], total: int, count: int, offset: int) -> dict:
"""A `searchset` Bundle with the page's entries, the total and the `self`, `next` and `previous` links."""
def link(relation: str, at: int) -> dict:
args = [(k, v) for k, v in request.args.items(multi=True) if k not in ("_count", "_offset")]
return {"relation": relation, "url": f"{request.base_url}?{urlencode([*args, ('_count', count), ('_offset', at)])}"}
links = [link("self", offset)]
if offset + count < total:
links.append(link("next", offset + count))
if offset > 0:
links.append(link("previous", max(0, offset - count)))
return {"resourceType": "Bundle", "type": "searchset", "total": total, "link": links, "entry": entries}
def fhir_base() -> str:
"""This request's FHIR endpoint, `…/<domain>/fhir/`: what a `fullUrl` is relative to."""
url = request.base_url
return url[:url.index("/fhir/") + len("/fhir/")] if "/fhir/" in url else url.rstrip("/") + "/"
def entry(resource: dict, mode: str | None = "match") -> dict:
"""A Bundle entry: its `fullUrl` when the resource has an id, and its search mode in a searchset."""
item = {"resource": resource}
if "id" in resource:
item = {"fullUrl": f"{fhir_base()}{resource['resourceType']}/{resource['id']}", **item}
if mode:
item["search"] = {"mode": mode}
return item