hl7 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hl7/__init__.py ADDED
@@ -0,0 +1,69 @@
1
+ """python-hl7 is a simple library for parsing messages of Health Level 7
2
+ (HL7) version 2.x into Python objects.
3
+
4
+ * Documentation: http://python-hl7.readthedocs.org
5
+ * Source Code: http://github.com/johnpaulett/python-hl7
6
+ """
7
+
8
+ from .accessor import Accessor
9
+ from .containers import (
10
+ Batch,
11
+ Component,
12
+ Container,
13
+ Factory,
14
+ Field,
15
+ File,
16
+ Message,
17
+ Repetition,
18
+ Segment,
19
+ Sequence,
20
+ )
21
+ from .datatypes import parse_datetime
22
+ from .exceptions import (
23
+ HL7Exception,
24
+ MalformedBatchException,
25
+ MalformedFileException,
26
+ MalformedSegmentException,
27
+ ParseException,
28
+ )
29
+ from .parser import parse, parse_batch, parse_file, parse_hl7
30
+ from .util import generate_message_control_id, isbatch, isfile, ishl7, split_file
31
+
32
+ __version__ = "0.5.0"
33
+ __author__ = "John Paulett"
34
+ __email__ = "john -at- paulett.org"
35
+ __license__ = "BSD"
36
+ __copyright__ = "Copyright 2011, John Paulett <john -at- paulett.org>"
37
+
38
+ #: This is the HL7 Null value. It means that a field is present and blank.
39
+ NULL = '""'
40
+
41
+
42
+ __all__ = [
43
+ "parse",
44
+ "parse_hl7",
45
+ "parse_batch",
46
+ "parse_file",
47
+ "Sequence",
48
+ "Container",
49
+ "File",
50
+ "Batch",
51
+ "Message",
52
+ "Segment",
53
+ "Field",
54
+ "Repetition",
55
+ "Component",
56
+ "Factory",
57
+ "Accessor",
58
+ "ishl7",
59
+ "isbatch",
60
+ "isfile",
61
+ "split_file",
62
+ "generate_message_control_id",
63
+ "parse_datetime",
64
+ "HL7Exception",
65
+ "MalformedBatchException",
66
+ "MalformedFileException",
67
+ "MalformedSegmentException",
68
+ "ParseException",
69
+ ]
hl7/accessor.py ADDED
@@ -0,0 +1,108 @@
1
+ from collections import namedtuple
2
+
3
+
4
+ class Accessor(
5
+ namedtuple(
6
+ "Accessor",
7
+ [
8
+ "segment",
9
+ "segment_num",
10
+ "field_num",
11
+ "repeat_num",
12
+ "component_num",
13
+ "subcomponent_num",
14
+ ],
15
+ )
16
+ ):
17
+ __slots__ = ()
18
+
19
+ def __new__(
20
+ cls,
21
+ segment,
22
+ segment_num=1,
23
+ field_num=None,
24
+ repeat_num=None,
25
+ component_num=None,
26
+ subcomponent_num=None,
27
+ ):
28
+ """Create a new instance of Accessor for *segment*. Index numbers start from 1."""
29
+ return super().__new__(
30
+ cls,
31
+ segment,
32
+ segment_num,
33
+ field_num,
34
+ repeat_num,
35
+ component_num,
36
+ subcomponent_num,
37
+ )
38
+
39
+ @property
40
+ def key(self):
41
+ """Return the string accessor key that represents this instance"""
42
+ seg = (
43
+ self.segment
44
+ if self.segment_num == 1
45
+ else self.segment + str(self.segment_num)
46
+ )
47
+ return ".".join(
48
+ str(f)
49
+ for f in [
50
+ seg,
51
+ self.field_num,
52
+ self.repeat_num,
53
+ self.component_num,
54
+ self.subcomponent_num,
55
+ ]
56
+ if f is not None
57
+ )
58
+
59
+ def __str__(self):
60
+ return self.key
61
+
62
+ @classmethod
63
+ def parse_key(cls, key):
64
+ """Create an Accessor by parsing an accessor key.
65
+
66
+ The key is defined as:
67
+
68
+ | SEG[n]-Fn-Rn-Cn-Sn
69
+ | F Field
70
+ | R Repeat
71
+ | C Component
72
+ | S Sub-Component
73
+ |
74
+ | *Indexing is from 1 for compatibility with HL7 spec numbering.*
75
+
76
+ Example:
77
+
78
+ | PID.F1.R1.C2.S2 or PID.1.1.2.2
79
+ |
80
+ | PID (default to first PID segment, counting from 1)
81
+ | F1 (first after segment id, HL7 Spec numbering)
82
+ | R1 (repeat counting from 1)
83
+ | C2 (component 2 counting from 1)
84
+ | S2 (component 2 counting from 1)
85
+ """
86
+
87
+ def parse_part(keyparts, index, prefix):
88
+ if len(keyparts) > index:
89
+ num = keyparts[index]
90
+ if num[0].upper() == prefix:
91
+ num = num[1:]
92
+ return int(num)
93
+ else:
94
+ return None
95
+
96
+ parts = key.split(".")
97
+ segment = parts[0][:3]
98
+ if len(parts[0]) > 3:
99
+ segment_num = int(parts[0][3:])
100
+ else:
101
+ segment_num = 1
102
+ field_num = parse_part(parts, 1, "F")
103
+ repeat_num = parse_part(parts, 2, "R")
104
+ component_num = parse_part(parts, 3, "C")
105
+ subcomponent_num = parse_part(parts, 4, "S")
106
+ return cls(
107
+ segment, segment_num, field_num, repeat_num, component_num, subcomponent_num
108
+ )
hl7/client.py ADDED
@@ -0,0 +1,321 @@
1
+ import argparse
2
+ import io
3
+ import math
4
+ import os.path
5
+ import socket
6
+ import sys
7
+
8
+ import hl7
9
+
10
+ SB = b"\x0b" # <SB>, vertical tab
11
+ EB = b"\x1c" # <EB>, file separator
12
+ CR = b"\x0d" # <CR>, \r
13
+
14
+ FF = b"\x0c" # <FF>, new page form feed
15
+
16
+ RECV_BUFFER = 4096
17
+
18
+
19
+ class MLLPException(Exception):
20
+ pass
21
+
22
+
23
+ class MLLPClient:
24
+ """
25
+ A basic, blocking, HL7 MLLP client based upon :py:mod:`socket`.
26
+
27
+ MLLPClient implements two methods for sending data to the server.
28
+
29
+ * :py:meth:`MLLPClient.send` for raw data that already is wrapped in the
30
+ appropriate MLLP container (e.g. *<SB>message<EB><CR>*).
31
+ * :py:meth:`MLLPClient.send_message` will wrap the message in the MLLP
32
+ container
33
+
34
+ Can be used by the ``with`` statement to ensure :py:meth:`MLLPClient.close`
35
+ is called::
36
+
37
+ with MLLPClient(host, port) as client:
38
+ client.send_message('MSH|...')
39
+
40
+ MLLPClient takes an optional ``encoding`` parameter, defaults to UTF-8,
41
+ for encoding unicode messages [#]_.
42
+
43
+ MLLPClient also takes an optional ``timeout`` parameter, a positive number
44
+ of seconds. The default, ``None``, leaves the socket's timeout unchanged
45
+ (blocking, unless a global default was set with
46
+ :py:func:`socket.setdefaulttimeout`), so a server that never replies makes
47
+ :py:meth:`MLLPClient.send_message` wait forever. A ``timeout`` applies to
48
+ each socket operation (connect, send and receive) separately; the hostname
49
+ lookup is not covered. :py:exc:`TimeoutError` is raised when it expires.
50
+ After a timeout the reply may still arrive later, so close the client
51
+ rather than reuse it::
52
+
53
+ with MLLPClient(host, port, timeout=10) as client:
54
+ client.send_message('MSH|...')
55
+
56
+ .. [#] http://wiki.hl7.org/index.php?title=Character_Set_used_in_v2_messages
57
+ """
58
+
59
+ def __init__(self, host, port, encoding="utf-8", timeout=None):
60
+ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
61
+ try:
62
+ if timeout is not None:
63
+ self.socket.settimeout(timeout)
64
+ self.socket.connect((host, port))
65
+ except BaseException:
66
+ # no client object is returned, so nobody else can close it
67
+ self.socket.close()
68
+ raise
69
+ self.encoding = encoding
70
+
71
+ def __enter__(self):
72
+ return self
73
+
74
+ def __exit__(self, exc_type, exc_val, trackeback):
75
+ self.close()
76
+
77
+ def close(self):
78
+ """Release the socket connection"""
79
+ self.socket.close()
80
+
81
+ def send_message(self, message):
82
+ """Wraps a byte string, unicode string, or :py:class:`hl7.Message`
83
+ in a MLLP container and send the message to the server
84
+
85
+ If message is a byte string, we assume it is already encoded properly.
86
+ If message is unicode or :py:class:`hl7.Message`, it will be encoded
87
+ according to :py:attr:`hl7.client.MLLPClient.encoding`
88
+
89
+ """
90
+ if isinstance(message, bytes):
91
+ # Assume we have the correct encoding
92
+ binary = message
93
+ else:
94
+ # Encode the unicode message into a bytestring
95
+ if isinstance(message, hl7.Message):
96
+ message = str(message)
97
+ binary = message.encode(self.encoding)
98
+
99
+ # wrap in MLLP message container
100
+ data = SB + binary + EB + CR
101
+ return self.send(data)
102
+
103
+ def send(self, data):
104
+ """Low-level, direct access to the socket.send (data must be already
105
+ wrapped in an MLLP container). Blocks until the server returns the
106
+ full response, ending in *<EB><CR>*, which is returned as is, still
107
+ wrapped in its MLLP container.
108
+
109
+ Raises :py:exc:`MLLPException` if the server closes the connection
110
+ before the full response arrives, or :py:exc:`TimeoutError` if a
111
+ ``timeout`` was given and expires.
112
+ """
113
+ # upload the data
114
+ self.socket.sendall(data)
115
+ # wait for the ACK/NACK. The server may send it in several pieces, so
116
+ # keep reading until the MLLP end of message.
117
+ response = b""
118
+ while not response.endswith(EB + CR):
119
+ chunk = self.socket.recv(RECV_BUFFER)
120
+ if not chunk:
121
+ # report only the length, the response may hold patient data
122
+ raise MLLPException(
123
+ "connection closed before the full response was received "
124
+ f"({len(response)} bytes received)"
125
+ )
126
+ response += chunk
127
+ return response
128
+
129
+
130
+ # wrappers to make testing easier
131
+ def stdout(content):
132
+ # In Python 3, can't write bytes via sys.stdout.write
133
+ # http://bugs.python.org/issue18512
134
+ if isinstance(content, bytes):
135
+ out = sys.stdout.buffer
136
+ newline = b"\n"
137
+ else:
138
+ out = sys.stdout
139
+ newline = "\n"
140
+
141
+ out.write(content + newline)
142
+
143
+
144
+ def stdin():
145
+ return sys.stdin
146
+
147
+
148
+ def stderr():
149
+ return sys.stderr
150
+
151
+
152
+ def read_stream(stream):
153
+ """Buffer the stream and yield individual, stripped messages"""
154
+ _buffer = b""
155
+
156
+ while True:
157
+ data = stream.read(RECV_BUFFER)
158
+ if data == b"":
159
+ break
160
+ # usually should be broken up by EB, but I have seen FF separating
161
+ # messages
162
+ messages = (_buffer + data).split(EB if FF not in data else FF)
163
+
164
+ # whatever is in the last chunk is an uncompleted message, so put back
165
+ # into the buffer
166
+ _buffer = messages.pop(-1)
167
+
168
+ for m in messages:
169
+ yield m.strip(SB + CR)
170
+
171
+ if len(_buffer.strip()) > 0:
172
+ raise MLLPException("buffer not terminated: %s" % _buffer)
173
+
174
+
175
+ def read_loose(stream):
176
+ """Turn a HL7-like blob of text into a real HL7 messages"""
177
+ # look for the START_BLOCK to delineate messages
178
+ START_BLOCK = rb"MSH|^~\&|"
179
+
180
+ # load all the data
181
+ data = stream.read()
182
+
183
+ # Take out all the typical MLLP separators. In Python 3, iterating
184
+ # through a bytestring returns ints, so we need to filter out the int
185
+ # versions of the separators, then convert back from a list of ints to
186
+ # a bytestring.
187
+ # WARNING: There is an assumption here that we can treat the data as single bytes
188
+ # when filtering out the separators.
189
+ separators = [bs[0] for bs in [EB, FF, SB]]
190
+ data = bytes(b for b in data if b not in separators)
191
+ # Windows & Unix new lines to segment separators
192
+ data = data.replace(b"\r\n", b"\r").replace(b"\n", b"\r")
193
+
194
+ for m in data.split(START_BLOCK):
195
+ if not m:
196
+ # the first element will not have any data from the split
197
+ continue
198
+
199
+ # strip any trailing whitespace
200
+ m = m.strip(CR + b"\n ")
201
+
202
+ # re-insert the START_BLOCK, which was removed via the split
203
+ yield START_BLOCK + m
204
+
205
+
206
+ def _positive_timeout(value):
207
+ """argparse type for ``--timeout``: a finite number of seconds above 0."""
208
+ try:
209
+ seconds = float(value)
210
+ except ValueError:
211
+ raise argparse.ArgumentTypeError(f"invalid timeout: {value!r}") from None
212
+ if not math.isfinite(seconds) or seconds <= 0:
213
+ raise argparse.ArgumentTypeError(
214
+ f"timeout must be a positive number of seconds, got {value!r}"
215
+ )
216
+ return seconds
217
+
218
+
219
+ def mllp_send():
220
+ """Command line tool to send messages to an MLLP server"""
221
+ # set up the command line options
222
+ script_name = os.path.basename(sys.argv[0])
223
+ parser = argparse.ArgumentParser(usage=script_name + " [options] <server>")
224
+
225
+ parser.add_argument(
226
+ "--version",
227
+ action="store_true",
228
+ dest="version",
229
+ default=False,
230
+ help="print current version and exit",
231
+ )
232
+ parser.add_argument(
233
+ "-p",
234
+ "--port",
235
+ action="store",
236
+ type=int,
237
+ dest="port",
238
+ default=6661,
239
+ help="port to connect to",
240
+ )
241
+ parser.add_argument(
242
+ "--timeout",
243
+ action="store",
244
+ type=_positive_timeout,
245
+ dest="timeout",
246
+ default=None,
247
+ help="seconds to wait for the server before giving up (default: no timeout)",
248
+ )
249
+ parser.add_argument(
250
+ "-f",
251
+ "--file",
252
+ dest="filename",
253
+ help="read from FILE instead of stdin",
254
+ metavar="FILE",
255
+ )
256
+ parser.add_argument(
257
+ "-q",
258
+ "--quiet",
259
+ action="store_false",
260
+ dest="verbose",
261
+ default=True,
262
+ help="do not print status messages to stdout",
263
+ )
264
+ parser.add_argument(
265
+ "--loose",
266
+ action="store_true",
267
+ dest="loose",
268
+ default=False,
269
+ help=(
270
+ "allow file to be a HL7-like object (\\r\\n instead "
271
+ "of \\r). Requires that messages start with "
272
+ '"MSH|^~\\&|". Requires --file option (no stdin)'
273
+ ),
274
+ )
275
+ parser.add_argument("server", nargs="?")
276
+
277
+ options = parser.parse_args()
278
+
279
+ if options.version:
280
+ import hl7
281
+
282
+ stdout(hl7.__version__)
283
+ return
284
+
285
+ if options.server is not None:
286
+ host = options.server
287
+ else:
288
+ # server not present
289
+ parser.print_usage()
290
+ stderr().write("server required\n")
291
+ sys.exit(1)
292
+ return # for testing when sys.exit mocked
293
+
294
+ if options.filename is not None:
295
+ # Previously set stream to the open() handle, but then we did not
296
+ # close the open file handle. This new approach consumes the entire
297
+ # file into memory before starting to process, which is not required
298
+ # or ideal, since we can handle a stream
299
+ with open(options.filename, "rb") as f:
300
+ stream = io.BytesIO(f.read())
301
+ else:
302
+ if options.loose:
303
+ stderr().write("--loose requires --file\n")
304
+ sys.exit(1)
305
+ return # for testing when sys.exit mocked
306
+
307
+ stream = stdin()
308
+
309
+ with MLLPClient(host, options.port, timeout=options.timeout) as client:
310
+ message_stream = (
311
+ read_stream(stream) if not options.loose else read_loose(stream)
312
+ )
313
+
314
+ for message in message_stream:
315
+ result = client.send_message(message)
316
+ if options.verbose:
317
+ stdout(result)
318
+
319
+
320
+ if __name__ == "__main__":
321
+ mllp_send()