-
Notifications
You must be signed in to change notification settings - Fork 38
/
web.py
3184 lines (2879 loc) · 110 KB
/
web.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Client for interacting with a DICOMweb service over network using HTTP.
Facilitates access to data stored remotely on a server.
"""
import re
import logging
from enum import Enum
from http import HTTPStatus
from io import BytesIO
from typing import (
Any,
Callable,
Dict,
Iterator,
List,
Mapping,
Optional,
Set,
Sequence,
Union,
Tuple,
)
from urllib.parse import urlparse
from warnings import warn
from xml.etree.ElementTree import (
Element,
fromstring
)
import pydicom
import requests
import retrying
from dicomweb_client.uri import build_query_string, parse_query_parameters
logger = logging.getLogger(__name__)
def _load_xml_dataset(dataset: Element) -> pydicom.dataset.Dataset:
"""Load DICOM Data Set in DICOM XML format.
Parameters
----------
dataset: xml.etree.ElementTree.Element
parsed element tree
Returns
-------
pydicom.dataset.Dataset
data set
"""
ds = pydicom.Dataset()
for element in dataset:
keyword = element.attrib['keyword']
vr = element.attrib['vr']
value: Optional[Union[List[Any], str]]
if vr == 'SQ':
value = [
_load_xml_dataset(item)
for item in element
]
else:
value = list(element)
if len(value) == 1:
value = value[0].text.strip()
elif len(value) > 1:
value = [v.text.strip() for v in value]
else:
value = None
setattr(ds, keyword, value)
return ds
class _Transaction(Enum):
STORE = 'store'
SEARCH = 'search'
RETRIEVE = 'retrieve'
DELETE = 'delete'
class DICOMwebClient:
"""Class for connecting to and interacting with a DICOMweb RESTful service.
Attributes
----------
base_url: str
Unique resource locator of the DICOMweb service
scheme: str
Name of the scheme, e.g. ``"https"``
protocol: str
Name of the protocol, e.g. ``"https"``
host: str
IP address or DNS name of the machine that hosts the server
port: int
Number of the port to which the server listens
url_prefix: str
URL path prefix for DICOMweb services (part of `base_url`)
qido_url_prefix: Union[str, None]
URL path prefix for QIDO-RS (not part of `base_url`)
wado_url_prefix: Union[str, None]
URL path prefix for WADO-RS (not part of `base_url`)
stow_url_prefix: Union[str, None]
URL path prefix for STOW-RS (not part of `base_url`)
delete_url_prefix: Union[str, None]
URL path prefix for DELETE (not part of `base_url`)
"""
def set_chunk_size(self, chunk_size: int) -> None:
"""Set value of `chunk_size` attribute.
Parameters
----------
chunk_size: int
Maximum number of bytes that should be transferred per data chunk
when streaming data from the server using chunked transfer encoding
(used by ``iter_*()`` methods as well as the ``store_instances()``
method)
"""
self._chunk_size = chunk_size
def set_http_retry_params(
self,
retry: bool = True,
max_attempts: int = 5,
wait_exponential_multiplier: int = 1000,
retriable_error_codes: Tuple[HTTPStatus, ...] = (
HTTPStatus.TOO_MANY_REQUESTS,
HTTPStatus.REQUEST_TIMEOUT,
HTTPStatus.SERVICE_UNAVAILABLE,
HTTPStatus.GATEWAY_TIMEOUT,
)
) -> None:
"""Set parameters for HTTP retrying logic.
These parameters determine whether and how individual HTTP requests
will be retried in case the origin server responds with an error code
defined in `retriable_error_codes`.
The retrying method uses exponential back off using the multiplier
`wait_exponential_multiplier` for a max attempts defined by
`max_attempts`.
Parameters
----------
retry: bool, optional
Whether HTTP retrying should be performed, if it is set to
``False``, the rest of the parameters are ignored.
max_attempts: int, optional
The maximum number of request attempts.
wait_exponential_multiplier: float, optional
Exponential multiplier applied to delay between attempts in ms.
retriable_error_codes: tuple, optional
Tuple of HTTP error codes to retry if raised.
"""
self._http_retry = retry
if retry:
self._max_attempts = max_attempts
self._wait_exponential_multiplier = wait_exponential_multiplier
self._http_retrable_errors = retriable_error_codes
else:
self._max_attempts = 1
self._wait_exponential_multiplier = 1
self._http_retrable_errors = ()
def _is_retriable_http_error(
self,
response: requests.models.Response
) -> bool:
"""Determine whether the given response's status code is retriable.
Parameters
----------
response: requests.models.Response
HTTP response object returned by the request method.
Returns
-------
bool
Whether the HTTP request should be retried.
"""
return response.status_code in self._http_retrable_errors
def __init__(
self,
url: str,
session: Optional[requests.Session] = None,
qido_url_prefix: Optional[str] = None,
wado_url_prefix: Optional[str] = None,
stow_url_prefix: Optional[str] = None,
delete_url_prefix: Optional[str] = None,
proxies: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
callback: Optional[Callable] = None,
chunk_size: int = 10**6
) -> None:
"""Instatiate client.
Parameters
----------
url: str
Unique resource locator of the DICOMweb service consisting of
protocol, hostname (IP address or DNS name) of the machine that
hosts the service and optionally port number and path prefix
session: Union[requests.Session, None], optional
Session required to make connections to the DICOMweb service
(see ``dicomweb_client.session_utils`` module to create a valid
session if necessary)
qido_url_prefix: Union[str, None], optional
URL path prefix for QIDO RESTful services
wado_url_prefix: Union[str, None], optional
URL path prefix for WADO RESTful services
stow_url_prefix: Union[str, None], optional
URL path prefix for STOW RESTful services
delete_url_prefix: Union[str, None], optional
URL path prefix for DELETE RESTful services
proxies: Union[Dict[str, str], None], optional
Mapping of protocol or protocol + host to the URL of a proxy server
headers: Union[Dict[str, str], None], optional
Custom headers that should be included in request messages,
e.g., authentication tokens
callback: Union[Callable[[requests.Response, ...], requests.Response], None], optional
Callback function to manipulate responses generated from requests
(see `requests event hooks <http://docs.python-requests.org/en/master/user/advanced/#event-hooks>`_)
chunk_size: int, optional
Maximum number of bytes that should be transferred per data chunk
when streaming data from the server using chunked transfer encoding
(used by ``iter_*()`` methods as well as the ``store_instances()``
method); defaults to ``10**6`` bytes (1MB)
Warning
-------
Modifies the passed `session` (in particular header fields),
so be careful when reusing the session outside the scope of an instance.
Warning
-------
Choose the value of `chunk_size` carefully. A small value may cause
significant network communication and message parsing overhead.
""" # noqa: E501
if session is None:
logger.debug('initialize HTTP session')
session = requests.session()
self._session = session
self.base_url = url
if qido_url_prefix == '':
raise ValueError(
'Argument "qido_url_prefix" must not be a zero length string.'
)
self.qido_url_prefix = qido_url_prefix
if wado_url_prefix == '':
raise ValueError(
'Argument "wado_url_prefix" must not be a zero length string.'
)
self.wado_url_prefix = wado_url_prefix
if stow_url_prefix == '':
raise ValueError(
'Argument "stow_url_prefix" must not be a zero length string.'
)
self.stow_url_prefix = stow_url_prefix
if delete_url_prefix == '':
raise ValueError(
'Argument "delete_url_prefix" must not be a zero length string.'
)
self.delete_url_prefix = delete_url_prefix
# This regular expression extracts the scheme and host name from the URL
# and optionally the port number and prefix:
# <scheme>://<host>(:<port>)(/<prefix>)
# For example: "https://mydomain.com:443/wado-rs", where
# scheme="https", host="mydomain.com", port=443, prefix="wado-rs"
pattern = re.compile(
r'(?P<scheme>[https]+)://(?P<host>[^/:]+)'
r'(?::(?P<port>\d+))?(?:(?P<prefix>/[\w/]+))?'
)
match = re.match(pattern, self.base_url)
if match is None:
raise ValueError(f'Malformed URL: {self.base_url}')
url_components = urlparse(url)
self.scheme = url_components.scheme
self.protocol = self.scheme
if not self.scheme.startswith('http'):
raise ValueError(f'URL scheme "{self.scheme}" is not supported.')
try:
self.host = match.group('host')
port = match.group('port')
except AttributeError:
raise ValueError(f'Malformed URL: {self.base_url}')
if port:
self.port = int(port)
else:
if self.scheme == 'http':
self.port = 80
elif self.scheme == 'https':
self.port = 443
else:
raise ValueError(
f'URL scheme "{self.scheme}" is not supported.'
)
self.url_prefix = url_components.path
if headers is not None:
self._session.headers.update(headers)
if proxies is not None:
self._session.proxies = proxies
if callback is not None:
self._session.hooks = {'response': [callback, ]}
self._chunk_size = chunk_size
self.set_http_retry_params()
def _get_transaction_url(self, transaction: _Transaction) -> str:
"""Construct URL of a DICOMweb service transaction.
Parameters
----------
transaction: dicomweb_client.api._Transaction
Type of transaction
Returns
-------
str
Full URL for the given transaction
"""
transaction_url = str(self.base_url)
if transaction == _Transaction.SEARCH:
if self.qido_url_prefix is not None:
transaction_url += f'/{self.qido_url_prefix}'
elif transaction == _Transaction.RETRIEVE:
if self.wado_url_prefix is not None:
transaction_url += f'/{self.wado_url_prefix}'
elif transaction == _Transaction.STORE:
if self.stow_url_prefix is not None:
transaction_url += f'/{self.stow_url_prefix}'
elif transaction == _Transaction.DELETE:
if self.delete_url_prefix is not None:
transaction_url += f'/{self.delete_url_prefix}'
else:
raise ValueError(
f'Unsupported DICOMweb service "{transaction.value}".'
)
return transaction_url
def _get_studies_url(
self,
transaction: _Transaction,
study_instance_uid: Optional[str] = None
) -> str:
"""Construct URL for study-level requests.
Parameters
----------
transaction: dicomweb_client.api._Transaction
Type of transaction
study_instance_uid: Union[str, None], optional
Study Instance UID
Returns
-------
str
URL
"""
if study_instance_uid is not None:
url_template = '{transaction_url}/studies/{study_instance_uid}'
else:
url_template = '{transaction_url}/studies'
transaction_url = self._get_transaction_url(transaction)
return url_template.format(
transaction_url=transaction_url,
study_instance_uid=study_instance_uid
)
def _get_series_url(
self,
transaction: _Transaction,
study_instance_uid: Optional[str] = None,
series_instance_uid: Optional[str] = None
) -> str:
"""Construct URL for series-level requests.
Parameters
----------
transaction: dicomweb_client.api._Transaction
Type of transaction
study_instance_uid: Union[str, None], optional
Study Instance UID
series_instance_uid: Union[str, None], optional
Series Instance UID
Returns
-------
str
URL
"""
if study_instance_uid is not None:
url_template = self._get_studies_url(
transaction,
study_instance_uid
)
if series_instance_uid is not None:
url_template += '/series/{series_instance_uid}'
else:
url_template += '/series'
else:
if series_instance_uid is not None:
logger.warning(
'series UID is ignored because study UID is undefined'
)
url_template = '{transaction_url}/series'
transaction_url = self._get_transaction_url(transaction)
return url_template.format(
transaction_url=transaction_url,
series_instance_uid=series_instance_uid
)
def _get_instances_url(
self,
transaction: _Transaction,
study_instance_uid: Optional[str] = None,
series_instance_uid: Optional[str] = None,
sop_instance_uid: Optional[str] = None
) -> str:
"""Construct URL for instance-level requests.
Parameters
----------
transaction: dicomweb_client.api._Transaction
Type of transaction
study_instance_uid: Union[str, None], optional
Study Instance UID
series_instance_uid: Union[str, None], optional
Series Instance UID
sop_instance_uid: Union[str, None], optional
SOP Instance UID
Returns
-------
str
URL
"""
if study_instance_uid is not None and series_instance_uid is not None:
url_template = self._get_series_url(
transaction,
study_instance_uid,
series_instance_uid
)
url_template += '/instances'
if sop_instance_uid is not None:
url_template += '/{sop_instance_uid}'
elif study_instance_uid is not None:
if sop_instance_uid is not None:
logger.warning(
'SOP Instance UID is ignored because Series Instance UID '
'is undefined'
)
url_template = self._get_studies_url(
transaction,
study_instance_uid
)
url_template += '/instances'
else:
if sop_instance_uid is not None:
logger.warning(
'SOP Instance UID is ignored because Study/Series '
'Instance UID are undefined'
)
url_template = '{transaction_url}/instances'
transaction_url = self._get_transaction_url(transaction)
return url_template.format(
transaction_url=transaction_url,
sop_instance_uid=sop_instance_uid
)
def _http_get(
self,
url: str,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
stream: bool = False
) -> requests.models.Response:
"""Perform an HTTP GET request.
Parameters
----------
url: str
Unique resource locator
params: Union[Dict[str, Any], None], optional
Query parameters
headers: Union[Dict[str, str], None], optional
Request message headers
stream: bool, optional
Whether data should be streamed (i.e., requested using chunked
transfer encoding)
Returns
-------
requests.models.Response
Response message
"""
@retrying.retry(
retry_on_result=self._is_retriable_http_error,
wait_exponential_multiplier=self._wait_exponential_multiplier,
stop_max_attempt_number=self._max_attempts
)
def _invoke_get_request(
url: str,
headers: Optional[Dict[str, str]] = None
) -> requests.models.Response:
logger.debug(f'GET: {url} {headers}')
# Setting stream allows for retrieval of data using chunked transer
# encoding. The iter_content() method can be used to iterate over
# chunks. If stream is not set, iter_content() will return the
# full payload at once.
return self._session.get(url=url, headers=headers, stream=stream)
if headers is None:
headers = {}
if not stream:
headers['Host'] = self.host
url += build_query_string(params)
if stream:
logger.debug('use chunked transfer encoding')
response = _invoke_get_request(url, headers)
logger.debug(f'request status code: {response.status_code}')
response.raise_for_status()
# The server may not return all results, but rather include a warning
# header to notify that client that there are remaining results.
# (see DICOM Part 3.18 Section 6.7.1.2)
if 'Warning' in response.headers:
logger.warning(response.headers['Warning'])
return response
def _http_get_application_json(
self,
url: str,
params: Optional[Dict[str, Any]] = None,
stream: bool = False,
get_remaining: bool = False
) -> List[Dict[str, dict]]:
"""GET a resource with "applicaton/dicom+json" media type.
Parameters
----------
url: str
Unique resource locator
params: Union[Dict[str, Any], None], optional
Query parameters
stream: bool, optional
Whether data should be streamed (i.e., requested using chunked
transfer encoding)
get_remaining: bool, optional
Whether remaining data should also be requested
Returns
-------
List[str, dict]
Content of HTTP message body in DICOM JSON format
"""
def get(url, params, stream):
response = self._http_get(
url,
params=params,
headers={'Accept': 'application/dicom+json, application/json'},
stream=stream
)
if response.content:
response.encoding = 'UTF-8'
decoded_response = response.json()
# All metadata resources are expected to be sent as a JSON
# array of DICOM data sets. However, some origin servers may
# incorrectly sent an individual data set.
if isinstance(decoded_response, dict):
return [decoded_response]
return decoded_response
return []
if get_remaining:
results = []
if params is None:
params = {}
params['offset'] = params.get('offset', 0)
while True:
subset = get(url, params, stream)
if len(subset) == 0:
break
results.extend(subset)
params['offset'] += len(subset)
return results
else:
return get(url, params, stream)
@classmethod
def _extract_part_content(cls, part: bytes) -> Union[bytes, None]:
"""Extract the content of a single part of a multipart response message.
Parameters
----------
part: bytes
Individual part of a multipart message
Returns
-------
Union[bytes, None]
Content of the message part or ``None`` in case the message
part is empty
Raises
------
ValueError
When the message part is not CRLF CRLF terminated
"""
if part in (b'', b'--', b'\r\n') or part.startswith(b'--\r\n'):
return None
idx = part.index(b'\r\n\r\n')
if idx > -1:
return part[idx + 4:]
raise ValueError('Message part does not contain CRLF CRLF')
def _decode_multipart_message(
self,
response: requests.Response,
stream: bool
) -> Iterator[bytes]:
"""Decode extracted parts of a multipart response message.
Parameters
----------
response: requests.Response
Response message
stream: bool
Whether data should be streamed (i.e., requested using chunked
transfer encoding)
Returns
-------
Iterator[bytes]
Message parts
"""
logger.debug('decode multipart message')
logger.debug('decode message header')
content_type = response.headers['content-type']
media_type, *ct_info = [ct.strip() for ct in content_type.split(';')]
if media_type.lower() != 'multipart/related':
raise ValueError(
f'Unexpected media type: "{media_type}". '
'Expected "multipart/related".'
)
for item in ct_info:
attr, _, value = item.partition('=')
if attr.lower() == 'boundary':
boundary = value.strip('"').encode('utf-8')
break
else:
# Some servers set the media type to multipart but don't provide a
# boundary and just send a single frame in the body - return as is.
yield response.content
return
marker = b''.join((b'--', boundary))
delimiter = b''.join((b'\r\n', marker))
data = bytearray()
j = 0
with response:
logger.debug('decode message content')
if stream:
iterator = response.iter_content(chunk_size=self._chunk_size)
else:
iterator = iter([response.content])
for i, chunk in enumerate(iterator):
if stream:
logger.debug(f'decode message content chunk #{i}')
data += chunk
prev_part_index = 0
while True:
delimiter_index = data.find(delimiter, prev_part_index)
if delimiter_index < 0:
break
logger.debug(f'decode message part #{j}')
content = self._extract_part_content(
data[prev_part_index:delimiter_index]
)
prev_part_index = delimiter_index + len(delimiter)
j += 1
if content is not None:
logger.debug(
f'extracted {len(content)} bytes from part #{j}'
)
yield content
data = data[prev_part_index:]
content = self._extract_part_content(data)
if content is not None:
yield content
@classmethod
def _encode_multipart_message(
cls,
content: Sequence[bytes],
content_type: str
) -> bytes:
"""Encode the payload of a multipart response message.
Parameters
----------
content: Sequence[bytes]
Content of each part
content_type: str
Content type of the multipart HTTP request message
Returns
-------
bytes
HTTP request message body
"""
media_type, *ct_info = [ct.strip() for ct in content_type.split(';')]
if media_type != 'multipart/related':
raise ValueError(
'No "multipart/related" usage found in content type field'
)
parameters = {}
for item in ct_info:
name, value = item.split('=')
parameters[name.lower()] = value.strip('"')
try:
content_type = parameters['type']
except KeyError:
raise ValueError(
'No "type" parameter in found in content-type field'
)
try:
boundary = parameters['boundary']
except KeyError:
raise ValueError(
'No "boundary" parameter in found in content-type field'
)
with BytesIO() as b:
for part in content:
b.write(f'\r\n--{boundary}'.encode('utf-8'))
b.write(
f'\r\nContent-Type: {content_type}\r\n\r\n'.encode('utf-8')
)
b.write(part)
b.write(f'\r\n--{boundary}--'.encode('utf-8'))
return b.getvalue()
@classmethod
def _assert_media_type_is_valid(cls, media_type: str):
"""Assert that a given media type is valid.
Parameters
----------
media_type: str
Media type
Raises
------
ValueError
When `media_type` is invalid
"""
error_message = f'Not a valid media type: "{media_type}"'
sep_index = media_type.find('/')
if sep_index == -1:
raise ValueError(error_message)
media_type_type = media_type[:sep_index]
if media_type_type not in {
'*',
'application',
'image',
'text',
'video',
}:
raise ValueError(error_message)
if media_type.find('/', sep_index + 1) > 0:
raise ValueError(error_message)
@classmethod
def _build_range_header_field_value(
cls,
byte_range: Optional[Tuple[int, int]] = None
) -> str:
"""Build a range header field value for a request message.
Parameters
----------
byte_range: Union[Tuple[int, int], None], optional
Start and end of byte range
Returns
-------
str
Range header field value
"""
if byte_range is not None:
start = str(byte_range[0])
try:
end = str(byte_range[1])
except IndexError:
end = ''
range_header_field_value = f'bytes={start}-{end}'
else:
range_header_field_value = 'bytes=0-'
return range_header_field_value
@classmethod
def _build_accept_header_field_value(
cls,
media_types: Union[Tuple[Union[str, Tuple[str, str]], ...], None],
supported_media_types: Set[str]
) -> str:
"""Build an accept header field value for a request message.
Parameters
----------
media_types: Union[Tuple[str], None]
Acceptable media types
supported_media_types: Set[str]
Supported media types
Returns
-------
str
Accept header field value
"""
if not isinstance(media_types, (list, tuple, set)):
raise TypeError(
'Acceptable media types must be provided as a sequence.'
)
field_value_parts = []
for media_type in media_types:
if not isinstance(media_type, str):
raise TypeError(
f'Media type "{media_type}" is not supported for '
'requested resource'
)
cls._assert_media_type_is_valid(media_type)
if media_type not in supported_media_types:
raise ValueError(
f'Media type "{media_type}" is not supported for '
'requested resource'
)
field_value_parts.append(media_type)
return ', '.join(field_value_parts)
@classmethod
def _build_multipart_accept_header_field_value(
cls,
media_types: Union[Tuple[Union[str, Tuple[str, str]], ...], None],
supported_media_types: Union[
Mapping[str, Union[str, Tuple[str, ...]]], Set[str]
]
) -> str:
"""Build an accept header field value for a multipart request message.
Parameters
----------
media_types: Union[Tuple[Union[str, Tuple[str, str]], ...], None]
Acceptable media types and optionally the UIDs of the corresponding
transfer syntaxes
supported_media_types: Union[Mapping[str, Union[str, Tuple[str, ...]]], Set[str]]
Set of supported media types or mapping of transfer syntaxes
to their corresponding media types
Returns
-------
str
Accept header field value
""" # noqa: E501
if not isinstance(media_types, (list, tuple, set)):
raise TypeError(
'Acceptable media types must be provided as a sequence.'
)
field_value_parts = []
for item in media_types:
if isinstance(item, str):
media_type = item
transfer_syntax_uid = None
else:
media_type = item[0]
try:
transfer_syntax_uid = item[1]
except IndexError:
transfer_syntax_uid = None
cls._assert_media_type_is_valid(media_type)
field_value = f'multipart/related; type="{media_type}"'
if isinstance(supported_media_types, dict):
media_type_in_supported_media_types = any(
media_type == supported_media_types
if isinstance(supported_media_types, str)
else media_type in supported_media_types
for supported_media_types in supported_media_types.values()
)
if not media_type_in_supported_media_types:
if not (media_type.endswith('/*') or
media_type.endswith('/')):
raise ValueError(
f'Media type "{media_type}" is not supported for '
'requested resource.'
)
if transfer_syntax_uid is not None:
if transfer_syntax_uid != '*':
if transfer_syntax_uid not in supported_media_types:
raise ValueError(
f'Transfer syntax "{transfer_syntax_uid}" '
'is not supported for requested resource.'
)
expected_media_types = supported_media_types[
transfer_syntax_uid
]
if not isinstance(expected_media_types, tuple):
expected_media_types = (expected_media_types, )
if media_type not in expected_media_types:
have_same_type = next(
(
cls._same_media_type(
media_type, expected_media_type
)
for expected_media_type
in expected_media_types
),
False
)
if (have_same_type and
(media_type.endswith('/*') or
media_type.endswith('/'))):
continue
raise ValueError(
f'Transfer syntax "{transfer_syntax_uid}" '
'is not supported for media '
f'type "{media_type}".'
)
field_value += f'; transfer-syntax={transfer_syntax_uid}'
else:
if media_type not in supported_media_types:
raise ValueError(
f'Media type "{media_type}" is not supported for '
'requested resource.'
)
field_value_parts.append(field_value)
return ', '.join(field_value_parts)
def _http_get_multipart_application_dicom(
self,
url: str,
media_types: Optional[Tuple[Union[str, Tuple[str, str]], ...]] = None,
params: Optional[Dict[str, Any]] = None,
stream: bool = False
) -> Iterator[pydicom.dataset.Dataset]:
"""GET a multipart resource with "applicaton/dicom" media type.
Parameters
----------
url: str
Unique resource locator
media_types: Union[Tuple[Union[str, Tuple[str, str]], ...], None], optional
Acceptable media types and optionally the UIDs of the
corresponding transfer syntaxes, (defaults to
``("application/dicom", "1.2.840.10008.1.2.1")``)
params: Union[Dict[str, Any], None], optional
Additional HTTP GET query parameters
stream: bool, optional
Whether data should be streamed (i.e., requested using chunked
transfer encoding)
Returns
-------
Iterator[pydicom.dataset.Dataset]
DICOM data sets
""" # noqa: E501
default_media_type = 'application/dicom'
supported_media_types = {
'1.2.840.10008.1.2.1': default_media_type,
'1.2.840.10008.1.2.5': default_media_type,
'1.2.840.10008.1.2.4.50': default_media_type,
'1.2.840.10008.1.2.4.51': default_media_type,
'1.2.840.10008.1.2.4.57': default_media_type,
'1.2.840.10008.1.2.4.70': default_media_type,