comparison Tests/Toolbox.py @ 83:3f2170efa8d2

patches for python3
author Sebastien Jodogne <s.jodogne@gmail.com>
date Thu, 23 Jun 2016 18:04:59 +0200
parents 97acfdf0dbce
children 2af6c0fb850d
comparison
equal deleted inserted replaced
82:91e2ed032f96 83:3f2170efa8d2
24 import os 24 import os
25 import re 25 import re
26 import signal 26 import signal
27 import subprocess 27 import subprocess
28 import threading 28 import threading
29 import sys
29 import time 30 import time
30 import zipfile 31 import zipfile
31 32
32 from PIL import Image 33 from PIL import Image
33 from urllib import urlencode 34
34 35 if (sys.version_info >= (3, 0)):
35 36 from urllib.parse import urlencode
36 # http://stackoverflow.com/a/1313868/881731 37 from io import StringIO
37 try: 38 from io import BytesIO
38 from cStringIO import StringIO 39
39 except: 40 else:
40 from StringIO import StringIO 41 from urllib import urlencode
42
43 # http://stackoverflow.com/a/1313868/881731
44 try:
45 from cStringIO import StringIO
46 except:
47 from StringIO import StringIO
48
49
50 def _DecodeJson(s):
51 t = s
52
53 if (sys.version_info >= (3, 0)):
54 try:
55 t = s.decode()
56 except:
57 pass
58
59 try:
60 return json.loads(t)
61 except:
62 return t
41 63
42 64
43 def DefineOrthanc(server = 'localhost', 65 def DefineOrthanc(server = 'localhost',
44 restPort = 8042, 66 restPort = 8042,
45 username = None, 67 username = None,
88 (resp, content) = DoGetRaw(orthanc, uri, data = data, body = body, headers = headers) 110 (resp, content) = DoGetRaw(orthanc, uri, data = data, body = body, headers = headers)
89 111
90 if not (resp.status in [ 200 ]): 112 if not (resp.status in [ 200 ]):
91 raise Exception(resp.status) 113 raise Exception(resp.status)
92 else: 114 else:
93 try: 115 return _DecodeJson(content)
94 return json.loads(content)
95 except:
96 return content
97 116
98 def _DoPutOrPost(orthanc, uri, method, data, contentType, headers): 117 def _DoPutOrPost(orthanc, uri, method, data, contentType, headers):
99 http = httplib2.Http() 118 http = httplib2.Http()
100 http.follow_redirects = False 119 http.follow_redirects = False
101 _SetupCredentials(orthanc, http) 120 _SetupCredentials(orthanc, http)
102 121
103 if isinstance(data, str): 122 if isinstance(data, (str, bytearray, bytes)):
104 body = data 123 body = data
105 if len(contentType) != 0: 124 if len(contentType) != 0:
106 headers['content-type'] = contentType 125 headers['content-type'] = contentType
107 else: 126 else:
108 body = json.dumps(data) 127 body = json.dumps(data)
114 body = body, 133 body = body,
115 headers = headers) 134 headers = headers)
116 if not (resp.status in [ 200, 302 ]): 135 if not (resp.status in [ 200, 302 ]):
117 raise Exception(resp.status) 136 raise Exception(resp.status)
118 else: 137 else:
119 try: 138 return _DecodeJson(content)
120 return json.loads(content)
121 except:
122 return content
123 139
124 def DoDelete(orthanc, uri): 140 def DoDelete(orthanc, uri):
125 http = httplib2.Http() 141 http = httplib2.Http()
126 http.follow_redirects = False 142 http.follow_redirects = False
127 _SetupCredentials(orthanc, http) 143 _SetupCredentials(orthanc, http)
128 144
129 resp, content = http.request(orthanc['Url'] + uri, 'DELETE') 145 resp, content = http.request(orthanc['Url'] + uri, 'DELETE')
130 if not (resp.status in [ 200 ]): 146 if not (resp.status in [ 200 ]):
131 raise Exception(resp.status) 147 raise Exception(resp.status)
132 else: 148 else:
133 try: 149 return _DecodeJson(content)
134 return json.loads(content)
135 except:
136 return content
137 150
138 def DoPut(orthanc, uri, data = {}, contentType = ''): 151 def DoPut(orthanc, uri, data = {}, contentType = ''):
139 return _DoPutOrPost(orthanc, uri, 'PUT', data, contentType, {}) 152 return _DoPutOrPost(orthanc, uri, 'PUT', data, contentType, {})
140 153
141 def DoPost(orthanc, uri, data = {}, contentType = '', headers = {}): 154 def DoPost(orthanc, uri, data = {}, contentType = '', headers = {}):
143 156
144 def GetDatabasePath(filename): 157 def GetDatabasePath(filename):
145 return os.path.join(os.path.dirname(__file__), '..', 'Database', filename) 158 return os.path.join(os.path.dirname(__file__), '..', 'Database', filename)
146 159
147 def UploadInstance(orthanc, filename): 160 def UploadInstance(orthanc, filename):
148 f = open(GetDatabasePath(filename), 'rb') 161 with open(GetDatabasePath(filename), 'rb') as f:
149 d = f.read() 162 d = f.read()
150 f.close() 163
151 return DoPost(orthanc, '/instances', d, 'application/dicom') 164 return DoPost(orthanc, '/instances', d, 'application/dicom')
152 165
153 def UploadFolder(orthanc, path): 166 def UploadFolder(orthanc, path):
154 for i in os.listdir(GetDatabasePath(path)): 167 for i in os.listdir(GetDatabasePath(path)):
155 try: 168 try:
172 return m.hexdigest() 185 return m.hexdigest()
173 186
174 def GetImage(orthanc, uri, headers = {}): 187 def GetImage(orthanc, uri, headers = {}):
175 # http://www.pythonware.com/library/pil/handbook/introduction.htm 188 # http://www.pythonware.com/library/pil/handbook/introduction.htm
176 data = DoGet(orthanc, uri, headers = headers) 189 data = DoGet(orthanc, uri, headers = headers)
177 return Image.open(StringIO(data)) 190 if (sys.version_info >= (3, 0)):
191 return Image.open(BytesIO(data))
192 else:
193 return Image.open(StringIO(data))
178 194
179 def GetArchive(orthanc, uri): 195 def GetArchive(orthanc, uri):
180 # http://stackoverflow.com/a/1313868/881731 196 # http://stackoverflow.com/a/1313868/881731
181 s = DoGet(orthanc, uri) 197 s = DoGet(orthanc, uri)
182 return zipfile.ZipFile(StringIO(s), "r") 198
199 if (sys.version_info >= (3, 0)):
200 return zipfile.ZipFile(BytesIO(s), "r")
201 else:
202 return zipfile.ZipFile(StringIO(s), "r")
183 203
184 def IsDefinedInLua(orthanc, name): 204 def IsDefinedInLua(orthanc, name):
185 s = DoPost(orthanc, '/tools/execute-script', 'print(type(%s))' % name, 'application/lua') 205 s = DoPost(orthanc, '/tools/execute-script', 'print(type(%s))' % name, 'application/lua')
186 return (s.strip() != 'nil') 206 return (s.strip() != 'nil')
187 207
222 if error != None: 242 if error != None:
223 # http://stackoverflow.com/a/1489838/881731 243 # http://stackoverflow.com/a/1489838/881731
224 os._exit(-1) 244 os._exit(-1)
225 stop_event.wait(0.1) 245 stop_event.wait(0.1)
226 246
227 print 'Stopping the external command' 247 print('Stopping the external command')
228 external.terminate() 248 external.terminate()
229 external.communicate() # Wait for the command to stop 249 external.communicate() # Wait for the command to stop
230 250
231 def __init__(self, command, env = None): 251 def __init__(self, command, env = None):
232 self.thread_stop = threading.Event() 252 self.thread_stop = threading.Event()