python-hl7 API¶
-
hl7.
NULL
= '""'¶ This is the HL7 Null value. It means that a field is present and blank.
-
hl7.
parse
(lines, encoding='utf-8', factory=<class 'hl7.containers.Factory'>)¶ Returns a instance of the
hl7.Message
that allows indexed access to the data elements.A custom
hl7.Factory
subclass can be passed in to be used when constructing the message and it’s components.Note
HL7 usually contains only ASCII, but can use other character sets (HL7 Standards Document, Section 1.7.1), however as of v2.8, UTF-8 is the preferred character set 1.
python-hl7 works on Python unicode strings.
hl7.parse()
will accept unicode string or will attempt to convert bytestrings into unicode strings using the optionalencoding
parameter.encoding
defaults to UTF-8, so no work is needed for bytestrings in UTF-8, but for other character sets like ‘cp1252’ or ‘latin1’,encoding
must be set appropriately.>>> h = hl7.parse(message)
To decode a non-UTF-8 byte string:
hl7.parse(message, encoding='latin1')
- Return type
-
hl7.
parse_batch
(lines, encoding='utf-8', factory=<class 'hl7.containers.Factory'>)¶ Returns a instance of a
hl7.Batch
that allows indexed access to the messages.A custom
hl7.Factory
subclass can be passed in to be used when constructing the batch and it’s components.Note
HL7 usually contains only ASCII, but can use other character sets (HL7 Standards Document, Section 1.7.1), however as of v2.8, UTF-8 is the preferred character set 2.
python-hl7 works on Python unicode strings.
hl7.parse_batch()
will accept unicode string or will attempt to convert bytestrings into unicode strings using the optionalencoding
parameter.encoding
defaults to UTF-8, so no work is needed for bytestrings in UTF-8, but for other character sets like ‘cp1252’ or ‘latin1’,encoding
must be set appropriately.>>> h = hl7.parse_batch(message)
To decode a non-UTF-8 byte string:
hl7.parse_batch(message, encoding='latin1')
- Return type
-
hl7.
parse_file
(lines, encoding='utf-8', factory=<class 'hl7.containers.Factory'>)¶ Returns a instance of the
hl7.File
that allows indexed access to the batches.A custom
hl7.Factory
subclass can be passed in to be used when constructing the file and it’s components.Note
HL7 usually contains only ASCII, but can use other character sets (HL7 Standards Document, Section 1.7.1), however as of v2.8, UTF-8 is the preferred character set 3.
python-hl7 works on Python unicode strings.
hl7.parse_file()
will accept unicode string or will attempt to convert bytestrings into unicode strings using the optionalencoding
parameter.encoding
defaults to UTF-8, so no work is needed for bytestrings in UTF-8, but for other character sets like ‘cp1252’ or ‘latin1’,encoding
must be set appropriately.>>> h = hl7.parse_file(message)
To decode a non-UTF-8 byte string:
hl7.parse_file(message, encoding='latin1')
- Return type
-
hl7.
parse_hl7
(line, encoding='utf-8', factory=<class 'hl7.containers.Factory'>)¶ Returns a instance of the
hl7.Message
,hl7.Batch
orhl7.File
that allows indexed access to the data elements or messages or batches respectively.A custom
hl7.Factory
subclass can be passed in to be used when constructing the message/batch/file and it’s components.Note
HL7 usually contains only ASCII, but can use other character sets (HL7 Standards Document, Section 1.7.1), however as of v2.8, UTF-8 is the preferred character set 4.
python-hl7 works on Python unicode strings.
hl7.parse_hl7()
will accept unicode string or will attempt to convert bytestrings into unicode strings using the optionalencoding
parameter.encoding
defaults to UTF-8, so no work is needed for bytestrings in UTF-8, but for other character sets like ‘cp1252’ or ‘latin1’,encoding
must be set appropriately.>>> h = hl7.parse_hl7(message)
To decode a non-UTF-8 byte string:
hl7.parse_hl7(message, encoding='latin1')
- Return type
-
hl7.
ishl7
(line)¶ Determines whether a line looks like an HL7 message. This method only does a cursory check and does not fully validate the message.
- Return type
-
hl7.
isbatch
(line)¶ Batches are wrapped in BHS / BTS or have more than one message BHS = batch header segment BTS = batch trailer segment
-
hl7.
isfile
(line)¶ Files are wrapped in FHS / FTS, or may be a batch FHS = file header segment FTS = file trailer segment
-
hl7.
split_file
(hl7file)¶ Given a file, split out the messages. Does not do any validation on the message. Throws away batch and file segments.
-
hl7.
generate_message_control_id
()¶ Generate a unique 20 character message id.
See http://www.hl7resources.com/Public/index.html?a55433.htm
-
hl7.
parse_datetime
(value)¶ Parse hl7 DTM string
value
datetime.datetime
.value
is of the format YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]][+/-HHMM] or a ValueError will be raised.- Return type
:py:;class:datetime.datetime
Data Types¶
-
class
hl7.
Sequence
¶ Base class for sequences that can be indexed using 1-based index
-
__call__
(index, value=<object object>)¶ Support list access using HL7 compatible 1-based indices. Can be used to get and set values.
>>> s = hl7.Sequence([1, 2, 3, 4]) >>> s(1) == s[0] True >>> s(2, "new") >>> s [1, 'new', 3, 4]
-
-
class
hl7.
Container
(separator, sequence=[], esc='\', separators='r|~^&', factory=None)¶ Abstract root class for the parts of the HL7 message.
-
__str__
()¶ Return str(self).
-
-
class
hl7.
Accessor
¶ -
static
__new__
(cls, segment, segment_num=1, field_num=None, repeat_num=None, component_num=None, subcomponent_num=None)¶ Create a new instance of Accessor for segment. Index numbers start from 1.
-
_asdict
()¶ Return a new OrderedDict which maps field names to their values.
-
classmethod
_make
(iterable)¶ Make a new Accessor object from a sequence or iterable
-
_replace
(**kwds)¶ Return a new Accessor object replacing specified fields with new values
-
property
component_num
¶ Alias for field number 4
-
property
field_num
¶ Alias for field number 2
-
property
key
¶ Return the string accessor key that represents this instance
-
classmethod
parse_key
(key)¶ Create an Accessor by parsing an accessor key.
The key is defined as:
SEG[n]-Fn-Rn-Cn-SnF FieldR RepeatC ComponentS Sub-ComponentIndexing is from 1 for compatibility with HL7 spec numbering.Example:
PID.F1.R1.C2.S2 or PID.1.1.2.2PID (default to first PID segment, counting from 1)F1 (first after segment id, HL7 Spec numbering)R1 (repeat counting from 1)C2 (component 2 counting from 1)S2 (component 2 counting from 1)
-
property
repeat_num
¶ Alias for field number 3
-
property
segment
¶ Alias for field number 0
-
property
segment_num
¶ Alias for field number 1
-
property
subcomponent_num
¶ Alias for field number 5
-
static
-
class
hl7.
Batch
(separator, sequence=[], esc='\', separators='r|~^&', factory=None)¶ Representation of an HL7 batch from the batch protocol. It contains a list of
hl7.Message
instances. It may contain BHS/BTShl7.Segment
instances.Batches may or may not be wrapped in BHS/BTS segements deliniating the start/end of the batch. These are optional.
-
__str__
()¶ Join a the child messages into a single string, separated by the self.separator. This method acts recursively, calling the children’s __unicode__ method. Thus
unicode()
is the approriate method for turning the python-hl7 representation of HL7 into a standard string.If this batch has BHS/BTS segments, they will be added to the beginning/end of the returned string.
-
create_component
(seq)¶ Create a new
hl7.Component
compatible with this container
-
create_header
()¶ Create a new
hl7.Segment
BHS compatible with this batch
-
create_message
(seq)¶ Create a new
hl7.Message
compatible with this container
-
create_repetition
(seq)¶ Create a new
hl7.Repetition
compatible with this container
-
create_segment
(seq)¶ Create a new
hl7.Segment
compatible with this container
-
create_trailer
()¶ Create a new
hl7.Segment
BHS compatible with this batch
-
property
header
¶ BHS
hl7.Segment
-
property
trailer
¶ BTS
hl7.Segment
-
-
class
hl7.
File
(separator, sequence=[], esc='\', separators='r|~^&', factory=None)¶ Representation of an HL7 file from the batch protocol. It contains a list of
hl7.Batch
instances. It may contain FHS/FTShl7.Segment
instances.Files may or may not be wrapped in FHS/FTS segements deliniating the start/end of the batch. These are optional.
-
__str__
()¶ Join a the child batches into a single string, separated by the self.separator. This method acts recursively, calling the children’s __unicode__ method. Thus
unicode()
is the approriate method for turning the python-hl7 representation of HL7 into a standard string.If this batch has FHS/FTS segments, they will be added to the beginning/end of the returned string.
-
create_component
(seq)¶ Create a new
hl7.Component
compatible with this container
-
create_header
()¶ Create a new
hl7.Segment
FHS compatible with this file
-
create_message
(seq)¶ Create a new
hl7.Message
compatible with this container
-
create_repetition
(seq)¶ Create a new
hl7.Repetition
compatible with this container
-
create_segment
(seq)¶ Create a new
hl7.Segment
compatible with this container
-
create_trailer
()¶ Create a new
hl7.Segment
FTS compatible with this file
-
property
header
¶ FHS
hl7.Segment
-
property
trailer
¶ FTS
hl7.Segment
-
-
class
hl7.
Message
(separator, sequence=[], esc='\', separators='r|~^&', factory=None)¶ Representation of an HL7 message. It contains a list of
hl7.Segment
instances.-
__getitem__
(key)¶ Index, segment-based or accessor lookup.
If key is an integer,
__getitem__
acts list a list, returning thehl7.Segment
held at that index:>>> h[1] [['PID'], ...]
If the key is a string of length 3,
__getitem__
acts like a dictionary, returning all segments whose segment_id is key (alias ofhl7.Message.segments()
).>>> h['OBX'] [[['OBX'], ['1'], ...]]
If the key is a string of length greater than 3, the key is parsed into an
hl7.Accessor
and passed tohl7.Message.extract_field()
.If the key is an
hl7.Accessor
, it is passed tohl7.Message.extract_field()
.
-
__setitem__
(key, value)¶ Index or accessor assignment.
If key is an integer,
__setitem__
acts list a list, setting thehl7.Segment
held at that index:>>> h[1] = hl7.Segment("|", [hl7.Field("^", ['PID'], [''])])
If the key is a string of length greater than 3, the key is parsed into an
hl7.Accessor
and passed tohl7.Message.assign_field()
.>>> h["PID.2"] = "NEW"
If the key is an
hl7.Accessor
, it is passed tohl7.Message.assign_field()
.
-
__str__
()¶ Join a the child containers into a single string, separated by the self.separator. This method acts recursively, calling the children’s __unicode__ method. Thus
unicode()
is the approriate method for turning the python-hl7 representation of HL7 into a standard string.>>> str(hl7.parse(message)) == message True
-
assign_field
(value, segment, segment_num=1, field_num=None, repeat_num=None, component_num=None, subcomponent_num=None)¶ Assign a value into a message using the tree based assignment notation. The segment must exist.
Extract a field using a future proofed approach, based on rules in: http://wiki.medical-objects.com.au/index.php/Hl7v2_parsing
-
create_ack
(ack_code='AA', message_id=None, application=None, facility=None)¶ Create an hl7 ACK response
hl7.Message
, per spec 2.9.2, for this message.See http://www.hl7standards.com/blog/2007/02/01/ack-message-original-mode-acknowledgement/
ack_code
options are one of AA (Application Accept), AR (Application Reject), AE (Application Error), CA (Commit Accept - Enhanced Mode), CR (Commit Reject - Enhanced Mode), or CE (Commit Error - Enhanced Mode) (see HL7 Table 0008 - Acknowledgment Code)message_id
control message ID for ACK, defaults to unique generated IDapplication
name of sending application, defaults to receiving application of messagefacility
name of sending facility, defaults to receiving facility of message
-
create_component
(seq)¶ Create a new
hl7.Component
compatible with this container
-
create_message
(seq)¶ Create a new
hl7.Message
compatible with this container
-
create_repetition
(seq)¶ Create a new
hl7.Repetition
compatible with this container
-
create_segment
(seq)¶ Create a new
hl7.Segment
compatible with this container
-
escape
(field, app_map=None)¶ See: http://www.hl7standards.com/blog/2006/11/02/hl7-escape-sequences/
To process this correctly, the full set of separators (MSH.1/MSH.2) needs to be known.
Pass through the message. Replace recognised characters with their escaped version. Return an ascii encoded string.
Functionality:
Replace separator characters (2.10.4)
replace application defined characters (2.10.7)
Replace non-ascii values with hex versions using HL7 conventions.
Incomplete:
replace highlight characters (2.10.3)
How to handle the rich text substitutions.
Merge contiguous hex values
-
extract_field
(segment, segment_num=1, field_num=1, repeat_num=1, component_num=1, subcomponent_num=1)¶ Extract a field using a future proofed approach, based on rules in: http://wiki.medical-objects.com.au/index.php/Hl7v2_parsing
‘PID|Field1|Component1^Component2|Component1^Sub-Component1&Sub-Component2^Component3|Repeat1~Repeat2’,
PID.F3.R1.C2.S2 = ‘Sub-Component2’PID.F4.R2.C1 = ‘Repeat1’Compatibility Rules:
If the parse tree is deeper than the specified path continue following the first child branch until a leaf of the tree is encountered and return that value (which could be blank).
Example:
PID.F3.R1.C2 = ‘Sub-Component1’ (assume .SC1)If the parse tree terminates before the full path is satisfied check each of the subsequent paths and if every one is specified at position 1 then the leaf value reached can be returned as the result.
PID.F4.R1.C1.SC1 = ‘Repeat1’ (ignore .SC1)
-
segment
(segment_id)¶ Gets the first segment with the segment_id from the parsed message.
>>> h.segment('PID') [['PID'], ...]
- Return type
-
segments
(segment_id)¶ Returns the requested segments from the parsed message that are identified by the segment_id (e.g. OBR, MSH, ORC, OBX).
>>> h.segments('OBX') [[['OBX'], ['1'], ...]]
- Return type
list of
hl7.Segment
-
unescape
(field, app_map=None)¶ See: http://www.hl7standards.com/blog/2006/11/02/hl7-escape-sequences/
To process this correctly, the full set of separators (MSH.1/MSH.2) needs to be known.
This will convert the identifiable sequences. If the application provides mapping, these are also used. Items which cannot be mapped are removed
For example, the App Map count provide N, H, Zxxx values
Chapter 2: Section 2.10
At the moment, this functionality can:
replace the parsing characters (2.10.4)
replace highlight characters (2.10.3)
replace hex characters. (2.10.5)
replace rich text characters (2.10.6)
replace application defined characters (2.10.7)
It cannot:
switch code pages / ISO IR character sets
-
-
class
hl7.
Segment
(separator, sequence=[], esc='\', separators='r|~^&', factory=None)¶ Second level of an HL7 message, which represents an HL7 Segment. Traditionally this is a line of a message that ends with a carriage return and is separated by pipes. It contains a list of
hl7.Field
instances.
-
class
hl7.
Field
(separator, sequence=[], esc='\', separators='r|~^&', factory=None)¶ Third level of an HL7 message, that traditionally is surrounded by pipes and separated by carets. It contains a list of strings or
hl7.Repetition
instances.
-
class
hl7.
Repetition
(separator, sequence=[], esc='\', separators='r|~^&', factory=None)¶ Fourth level of an HL7 message. A field can repeat. It contains a list of strings or
hl7.Component
instances.
-
class
hl7.
Component
(separator, sequence=[], esc='\', separators='r|~^&', factory=None)¶ Fifth level of an HL7 message. A component is a composite datatypes. It contains a list of string sub-components.
-
class
hl7.
Factory
¶ Factory used to create each type of Container.
A subclass can be used to create specialized subclasses of each container.
-
create_component
¶ Create an instance of
hl7.Component
alias of
Component
-
create_message
¶ Create an instance of
hl7.Message
alias of
Message
-
create_repetition
¶ Create an instance of
hl7.Repetition
alias of
Repetition
-
create_segment
¶ Create an instance of
hl7.Segment
alias of
Segment
-
MLLP Network Client¶
-
class
hl7.client.
MLLPClient
(host, port, encoding='utf-8')¶ A basic, blocking, HL7 MLLP client based upon
socket
.MLLPClient implements two methods for sending data to the server.
MLLPClient.send()
for raw data that already is wrapped in the appropriate MLLP container (e.g. <SB>message<EB><CR>).MLLPClient.send_message()
will wrap the message in the MLLP container
Can be used by the
with
statement to ensureMLLPClient.close()
is called:with MLLPClient(host, port) as client: client.send_message('MSH|...')
MLLPClient takes an optional
encoding
parameter, defaults to UTF-8, for encoding unicode messages 5.-
close
()¶ Release the socket connection
-
send
(data)¶ Low-level, direct access to the socket.send (data must be already wrapped in an MLLP container). Blocks until the server returns.
-
send_message
(message)¶ Wraps a byte string, unicode string, or
hl7.Message
in a MLLP container and send the message to the serverIf message is a byte string, we assume it is already encoded properly. If message is unicode or
hl7.Message
, it will be encoded according tohl7.client.MLLPClient.encoding
MLLP Asyncio¶
-
async
hl7.mllp.
open_hl7_connection
(host=None, port=None, *, loop=None, limit=65536, encoding=None, encoding_errors=None, **kwds)¶ A wrapper for loop.create_connection() returning a (reader, writer) pair.
The reader returned is a
hl7.mllp.HL7StreamReader
instance; the writer is ahl7.mllp.HL7StreamWriter
instance.The arguments are all the usual arguments to create_connection() except protocol_factory; most common are positional host and port, with various optional keyword arguments following.
Additional optional keyword arguments are loop (to set the event loop instance to use), limit (to set the buffer limit passed to the
hl7.mllp.HL7StreamReader
), encoding (to set the encoding on thehl7.mllp.HL7StreamReader
andhl7.mllp.HL7StreamWriter
) and encoding_errors (to set the encoding_errors on thehl7.mllp.HL7StreamReader
andhl7.mllp.HL7StreamWriter
).
-
async
hl7.mllp.
start_hl7_server
(client_connected_cb, host=None, port=None, *, loop=None, limit=65536, encoding=None, encoding_errors=None, **kwds)¶ Start a socket server, call back for each client connected.
The first parameter, client_connected_cb, takes two parameters: client_reader, client_writer. client_reader is a
hl7.mllp.HL7StreamReader
object, while client_writer is ahl7.mllp.HL7StreamWriter
object. This parameter can either be a plain callback function or a coroutine; if it is a coroutine, it will be automatically converted into a Task.The rest of the arguments are all the usual arguments to loop.create_server() except protocol_factory; most common are positional host and port, with various optional keyword arguments following.
The return value is the same as loop.create_server(). Additional optional keyword arguments are loop (to set the event loop instance to use) and limit (to set the buffer limit passed to the StreamReader).
The return value is the same as loop.create_server(), i.e. a Server object which can be used to stop the service.
-
class
hl7.mllp.
HL7StreamReader
(limit=65536, loop=None, encoding=None, encoding_errors=None)¶ -
async
readmessage
()¶ Reads a full HL7 message from the stream.
This will return an
hl7.Message
.If limit is reached, ValueError will be raised. In that case, if block termination separator was found, complete line including separator will be removed from internal buffer. Else, internal buffer will be cleared. Limit is compared against part of the line without separator.
If an invalid MLLP block is encountered,
hl7.mllp.InvalidBlockError
will be raised.
-
async
-
class
hl7.mllp.
HL7StreamWriter
(transport, protocol, reader, loop, encoding=None, encoding_errors=None)¶ -
writemessage
(message)¶ Writes an
hl7.Message
to the stream.
-
-
class
hl7.mllp.
InvalidBlockError
¶ An MLLP Block was received that violates MLLP protocol