protocols
The backend-neutral interface callers read an EHR through.
EHRDataService is one EHR connection, and PatientRecord is one patient's
record on it. A backend implements both.
The errors each method names are the backend-neutral types in
externals/ehr/exceptions.py, or subclasses of them.
On FHIR R4, a patient lookup raises an EHRRequestError (a FHIRR4APIError)
when the EHR answered it with an error status or an error OperationOutcome,
or with an answer the backend could not read: one that is not a Bundle or not
JSON, or a Patient that is not valid. A rejection (401) is one too, and is
also an EHRAuthenticationError. A 404 is not a failed request: a lookup
answered with one finds no patient (NoMatchingPatientError). NextGen raises
no EHRRequestError.
A record's fetches raise as PatientRecord says. On FHIR R4, a failed fetch
of clinical data is a FHIRR4GetPatientInfoError, which is an
EHRRequestError, whatever the failure, a 404 or an unreadable answer
included. These are not EHRRequestErrors:
- a fetch that raises
EHRFetchUnsupportedError(PatientRecordsays which); - two of a document listing's failures, as it raises the client's errors as
they are: a 404, which is fhirpy's
ResourceNotFound, and a 200 that is not JSON, ajson.JSONDecodeError(any other error status, and a 200 that is not a Bundle, is anEHRRequestError); json_dump's: it reads a failed search as no data, but raises a 200 that is not a Bundle as fhirpy'sInvalidResponse, and one that is not JSON as ajson.JSONDecodeError.
A patient lookup that fails for any other reason raises whatever error the backend or its transport raised, and those errors are not a closed list. They include:
- for both backends,
requestsconnection and timeout errors (requests.RequestException) left after the backend's retries; - for NextGen,
requests.HTTPError.
Classes
EHRDataService
class EHRDataService(*args, **kwargs):One EHR connection.
Built once per connection. It owns transport, auth and its give-up budget, timeouts, what is known about the server, retries and rechecks, the response cache and the provider's quirks. Callers ask it for patients and read their records; they never see a backend client.
Ancestors
Variables
supports_mrn_lookup : bool- Whetherfind_by_mrncan find patients on this EHR.
Methods
availability
def availability(self) ‑> EHRPreflightResult:Whether this EHR can be reached, before any patient is asked for.
find_by_mrn
def find_by_mrn( self, mrn: str | Sequence[str], *, system_qualified: bool = False,) ‑> PatientRecord:The record of the one patient holding this medical record number.
Given several, each value is one identifier, and they are tried in
turn, in the order given, one search each. The first value a patient
holds wins: different patients holding different values is not
non-specific, and the values after it are not searched. Only a value
no patient holds moves on to the next. Any other outcome for a value
(more than one patient holding it, a patient with no key, a rejection
or a failed search) is raised there, and the values after it are not
tried. When no patient holds any of them, NoMatchingPatientError is
raised, with the last value's miss as its __cause__.
Arguments
mrn: The identifier, or several to try in turn, each as a literalvalue: the backend escapes it for its search. Whitespace around a value is not part of it, and is stripped.system_qualified: Read a value holding exactly one|assystem|value, the value searched in that identifier system, as a person types it. A backend that searches identifiers without a system ignores it.
Raises
ValueError: If no identifier is given, or one is blank (empty or whitespace only).NoMatchingPatientError: If no patient holds any of them.NonSpecificPatientError: If more than one patient holds the value being tried.NoPatientIDError: If the patient holding the value being tried has no key.EHRAuthenticationError: If the EHR rejected the search.EHRConnectionError: If authentication has failed too often in a row for the run to go on.EHRRequestError: On FHIR R4, if the EHR answered the search with an error the backend reports as its own, such as an HTTP error status, or with an answer the backend could not read.Exception: Whatever else the backend or its transport raised. Not a closed list; it includesrequestsconnection and timeout errors left after the backend's retries, and for NextGenrequests.HTTPError, a rejection included.
find_patient
def find_patient( self, *, given: str | None, family: str | None, dob: str | date, narrows_last_search: bool = False,) ‑> PatientRecord:The record of the one patient with these names and date of birth.
Arguments
given: The given name searched on.family: The family name searched on.dob: The date of birth, as a date or aYYYY-MM-DDstring.narrows_last_search: The caller is narrowing the name search it just made for this date of birth. A backend that searched by date of birth may answer from that search's candidates instead of searching again.
Raises
NoMatchingPatientError: If no patient matches.NonSpecificPatientError: If more than one patient matches.NoPatientIDError: If the patient found has no key.EHRAuthenticationError: If the EHR rejected the search.EHRConnectionError: If authentication has failed too often in a row for the run to go on.EHRRequestError: On FHIR R4, if the EHR answered the search with an error the backend reports as its own, such as an HTTP error status, or with an answer the backend could not read.Exception: Whatever else the backend or its transport raised. Not a closed list; it includesrequestsconnection and timeout errors left after the backend's retries, and for NextGenrequests.HTTPError, a rejection included.
lister
def lister(self) ‑> BaseEHRPatientLister:A lister paging through this EHR's patients' keys.
Raises
EHRConnectionError: If authentication has failed too often in a row for the run to go on.
patient_by_id
def patient_by_id( self, patient_id: str,) ‑> PatientRecord:The record of the patient with this backend key.
Arguments
patient_id: The backend's key for the patient.
Raises
ValueError: If the key is blank (empty or whitespace only).NoMatchingPatientError: If no patient has that key.EHRAuthenticationError: If the EHR rejected the lookup.EHRConnectionError: If authentication has failed too often in a row for the run to go on.EHRRequestError: On FHIR R4, if the EHR answered the lookup with an error the backend reports as its own, such as an HTTP error status, or with an answer the backend could not read, or more than one patient has that key.Exception: Whatever else the backend or its transport raised. Not a closed list; it includesrequestsconnection and timeout errors left after the backend's retries, and for NextGenrequests.HTTPError, a rejection included.
record_for_id
def record_for_id( self, patient_id: str,) ‑> PatientRecord:A record for a backend key the caller already trusts.
Unlike patient_by_id, the patient is not confirmed to exist: the
record is built for the key as given. A caller uses it where a key is
all it has and the patient's data is wanted even when the patient
resource cannot be read. Its demographics are None.
The patient resource is read best effort, if the backend reads it at
all: found, it is the record's raw_patient. If no patient has the
key, or the read fails (an API error or an error answer, an answer
that cannot be read, or a connection or timeout error), the record has
none, and a failure is logged without the key. Only three outcomes
raise: the EHR rejecting the read, a second patient with that key, and
the connection's budget stop. A backend that builds the record without
a request (NextGen) has no read to fail.
Arguments
patient_id: The backend's key for the patient.
Raises
ValueError: If the key is blank (empty or whitespace only).EHRAuthenticationError: If the EHR rejected the request for the patient resource.EHRConnectionError: If authentication has failed too often in a row for the run to go on.EHRRequestError: On FHIR R4, if reading the patient resource found more than one patient with that key.
reset_auth_budget
def reset_auth_budget(self) ‑> None:Forget the authentication failures counted so far.
A caller starting a pass over patients calls this, so a pass that ended because authentication kept failing does not stop every later pass on the same connection before it sends a request. A backend that keeps no budget does nothing.
stats
def stats(self) ‑> EHRServiceStats:What this connection has counted so far.
PatientRecord
class PatientRecord(*args, **kwargs):One patient's record in an EHR.
Results honour the request: codes, categories, statuses and code types are filtered server-side where the backend can, and client-side where it cannot.
A failed fetch raises, unless the method names a result it gives instead
(such as get_patient_code_states's None fields, or the documents
download_documents failed to download, which it returns):
- A fetch the backend cannot serve at all raises
EHRFetchUnsupportedError, on both backends, with two exceptions on FHIR R4. Medications on a server that serves no medication type raiseFHIRR4MedicationsUnsupportedError, aGetPatientInfoErroronly.get_previous_encounter_detailson a server that does not serveEncounterraisesFHIRR4GetPatientInfoError, with the unsupported error as its__cause__. - A request FHIR R4 rejects as unauthenticated after refreshing its token
raises
EHRAuthenticationError. NextGen raises none: a request it rejects is a failed fetch. - Any other failed fetch of the patient's clinical data raises a
GetPatientInfoError:FHIRR4GetPatientInfoErroron FHIR R4 andNextGenGetPatientInfoErroron NextGen. A FHIR R4 server error or search given up on (each anEHRFetchUnavailableError) reaches the caller only as that error's__cause__. FHIR R4 conditions, procedures, observations, allergies and devices that were fetched but could not be read raiseFHIRR4DataErrorinstead. - A document listing whose request fails raises too, so that failure
does not read as no (more) documents, but not as a
GetPatientInfoError.download_documentsgiven noinfoslists the documents itself, downloading each batch as it is listed. On FHIR R4,document_infos, anddownload_documentsgiven noinfos, raise the client's errors as they are, so a server error is raised asFHIRR4ServerError, anEHRFetchUnavailableError; an answer that is not a Bundle (such as anOperationOutcomesent with a 200) is raised asFHIRR4APIError, with fhirpy'sInvalidResponseas its__cause__. On NextGen,download_documentsraisesNextGenEnterpriseAPIErrorfor a page whose request fails with an HTTP error, with that error as its__cause__; a next-page link of an unexpected form ends the listing with only a warning, so a listing cut short that way reads as complete. On both, a listing that fails part way raises after the documents of the batches before it were saved tosave_path; they are not returned.
Ancestors
Variables
demographics : RetrievedPatientDetailsJSON | None- The patient's names, date of birth, contacts and practitioners.
patient_id : str- The backend's key for the patient: opaque, passed back, not read.
raw_patient : Mapping[str, Any] | None- The backend's own patient resource as fetched, if one was.
Methods
acuity_in_documents_only
def acuity_in_documents_only(self) ‑> bool:Whether the server is marked as serving acuity only in documents.
While it is, the acuity code searches can be skipped and the patient's
documents read instead. Always False where acuity is not read from
documents.
document_infos
def document_infos(self) ‑> Iterable[list[EHRDocumentInfo]]:The patient's documents, in batches, without their content.
download_documents
def download_documents( self, save_path: Path, infos: Sequence[EHRDocumentInfo] | None = None,) ‑> tuple[list[DownloadedEHRDocumentInfo], list[FailedEHRDocumentInfo]]:Download the patient's documents to save_path.
Arguments
save_path: Where to save the documents.infos: The documents to download, fromdocument_infos; every document whenNone.
Returns The documents downloaded, and those that could not be.
get_document_acuity
def get_document_acuity( self, codes: Sequence[tuple[str | None, str]], *, observed: Mapping[Eye, date] | None = None,) ‑> DocumentAcuityResult:The visual acuity observations recorded in the patient's documents.
Arguments
codes: The(system, code)pairs of the acuity observations to read.observed: The date of each eye's newest best-corrected reading in the patient'sObservations. With both eyes given, the documents are listed but their CCDs downloaded only if one may be newer than the older of the two readings.None, or one eye, reads the CCDs as usual.
Returns The observations found, and whether the search was complete.
Raises
EHRFetchUnsupportedError: Only where the backend or provider does not read acuity from documents. Where it does, a server that will not list documents gives an incomplete result instead.Exception: The listing's errors, asdocument_infosraises them.
get_next_appointment
def get_next_appointment(self) ‑> datetime.date | None:The date of the patient's next appointment, if any.
get_patient_allergies
def get_patient_allergies(self) ‑> list[Allergy]:The patient's allergies and intolerances.
get_patient_associated_medical_practitioner
def get_patient_associated_medical_practitioner(self) ‑> str | None:The name of the practitioner associated with the patient, if any.
get_patient_code_states
def get_patient_code_states( self, *, include_medications: bool = False,) ‑> PatientCodeDetails:The patient's conditions, procedures and, optionally, medications.
Each is fetched on its own, so one failing costs only its own field,
which is None; unsupported_fields names those the backend cannot
serve at all.
Arguments
include_medications: Whether to fetch medications too.
get_patient_conditions
def get_patient_conditions( self, statuses_filter: list[ClinicalStatus] | None = None, code_types_filter: list[CodeSystems] | None = None,) ‑> list[Condition]:The patient's conditions.
Arguments
statuses_filter: Only conditions with one of these clinical statuses, or all whenNone.code_types_filter: Only codings in these code systems, or all whenNone.
get_patient_devices
def get_patient_devices(self) ‑> list[Device]:The devices recorded for the patient.
get_patient_medications
def get_patient_medications(self) ‑> list[Medication]:The patient's medications, from every medication source served.
get_patient_observations
def get_patient_observations( self, codes: Sequence[tuple[str | None, str]],) ‑> list[Observation]:The patient's observations with any of these codes.
Arguments
codes:(system, code)pairs; aNonesystem matches the code in any system.
get_patient_observations_by_category
def get_patient_observations_by_category( self, categories: Sequence[str],) ‑> list[Observation]:The patient's observations in any of these categories.
Arguments
categories: Observation category codes, such aslaboratory.
get_patient_procedures
def get_patient_procedures( self, statuses_filter: list[ProcedureStatus] | None = None, code_types_filter: list[CodeSystems] | None = None,) ‑> list[Procedure]:The patient's procedures.
Arguments
statuses_filter: Only procedures with one of these statuses, or all whenNone.code_types_filter: Only codings in these code systems, or all whenNone.
get_previous_appointment_details
def get_previous_appointment_details( self, include_maybe_attended: bool = True,) ‑> list[EHRAppointmentEncounter]:The patient's past appointments, oldest first.
Arguments
include_maybe_attended: Whether to include appointments whose attendance is not recorded.
get_previous_encounter_details
def get_previous_encounter_details( self, include_maybe_attended: bool = True,) ‑> list[EHRAppointmentEncounter]:The patient's past encounters, oldest first.
Arguments
include_maybe_attended: Whether to include encounters whose attendance is not recorded.
get_visual_acuity
def get_visual_acuity(self) ‑> Observation | None:The patient's most recent visual acuity reading, if any.
json_dump
def json_dump( self, save_path: Path, elements: Container[str] = frozenset({'procedures', 'patientInfo', 'encounters', 'medications', 'chart', 'appointments', 'conditions'}),) ‑> collections.abc.Mapping[str, typing.Any] | None:Save a JSON dump of the patient's record to save_path.
Its content is backend-specific: FHIR R4 dumps by resource type, NextGen by endpoint.
On FHIR R4, a search that fails reads as no data for its part of the
dump, except for these, which raise: a rejection, as
EHRAuthenticationError; a 200 that is not a Bundle (an empty body
included), as fhirpy's InvalidResponse; a 200 that is not JSON, as
json.JSONDecodeError; and a connection error left after the client's
retries, as it is.
Arguments
save_path: Where to save the dump.elements: The parts of the record to dump.
Returns
The dump, or None if there was nothing to dump.
reads_acuity_from_documents
def reads_acuity_from_documents(self) ‑> bool:Whether get_document_acuity reads acuity for this backend and provider.
record_acuity_sources
def record_acuity_sources(self, *, in_observations: bool, in_documents: bool) ‑> None:Record where this patient's visual acuity was found.
Evidence for acuity_in_documents_only, kept with what is known about
the server. Does nothing where acuity is not read from documents.
Arguments
in_observations: Whether the patient'sObservations held a reading for either eye.in_documents: Whether the patient's documents held a reading for either eye.
with_name
def with_name( self, *, given_name: str | None = None, family_name: str | None = None,) ‑> PatientRecord:The same patient's record, with these names in its demographics.
A name left as None keeps the record's own. A record with no
demographics gets demographics holding just its key and the names
given (none, given no names). This record is not changed.
Arguments
given_name: The given names to carry, joined by spaces.family_name: The family name to carry.