orthancInterface.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import urllib3
  2. #requests doesnt work as it lacks key password checking
  3. import json
  4. class orthancInterface:
  5. def init(self,fname):
  6. #fname is a file with configuration
  7. try:
  8. f=open(fname)
  9. except OSError as e:
  10. print("Confgiuration error: OS error({0}): {1}").format(e.errno, e.strerror)
  11. raise
  12. self.connectionConfig=json.load(f)
  13. self.http=urllib3.PoolManager()
  14. if 'SSL' in self.connectionConfig['orthanc']:
  15. sslConfig=self.connectionConfig['orthanc']['SSL']
  16. self.http = urllib3.PoolManager(\
  17. cert_file=sslConfig['user'],\
  18. cert_reqs='CERT_REQUIRED',\
  19. key_file=sslConfig['key'],\
  20. ca_certs=sslConfig['ca'])
  21. #password=self.connectionConfig['SSL']['keyPwd'],\ doesnt work until 1.25
  22. def getBasicAuth(self):
  23. user=self.connectionConfig['orthanc']['user']
  24. pwd=self.connectionConfig['orthanc']['password']
  25. return user+":"+pwd
  26. def getCoreURL(self):
  27. return self.connectionConfig['orthanc']['server']
  28. def get(self,url,binary=False):
  29. debug=False
  30. if debug:
  31. print("GET: {0}").format(url)
  32. print("as {0}").format(user)
  33. headers=urllib3.util.make_headers(basic_auth=self.getBasicAuth())
  34. try:
  35. if not binary:
  36. return self.http.request('GET',url,headers=headers)
  37. else:
  38. return self.http.request('GET',url,headers=headers,preload_content=False)
  39. #f contains json as a return value
  40. except urllib3.exceptions.HTTPError as e:
  41. print(e)
  42. def post(self,url,dataType,data):
  43. #dataType is typically json or octet-stream
  44. debug=False
  45. headers=urllib3.util.make_headers(basic_auth=self.getBasicAuth())
  46. headers['Content-Type']="application/"+dataType#for files
  47. #add csrf;also sets self.cookie
  48. #headers["X-LABKEY-CSRF"]=self.getCSRF()
  49. #doesn't seem like orthanc is big on security
  50. #headers["Cookie"]=self.cookie
  51. try:
  52. return self.http.request('POST',url,headers=headers,body=data)
  53. #f contains json as a return value
  54. except urllib3.exceptions.HTTPError as e:
  55. print(e)
  56. def put(self,url,data):
  57. debug=False
  58. if debug:
  59. print("PUT: {}").format(url)
  60. headers=urllib3.util.make_headers(basic_auth=self.getBasicAuth())
  61. headers["Content-Type"]="application/octet-stream"
  62. #add csrf
  63. #headers["X-LABKEY-CSRF"]=self.getCSRF()
  64. #headers["Cookie"]=self.cookie
  65. try:
  66. return self.http.request('PUT',url,headers=headers,body=data)
  67. #f contains json as a return value
  68. except urllib3.exceptions.HTTPError as e:
  69. print(e)