orthancInterface.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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:
  15. self.http = urllib3.PoolManager(\
  16. cert_file=self.connectionConfig['SSL']['user'],\
  17. cert_reqs='CERT_REQUIRED',\
  18. key_file=self.connectionConfig['SSL']['key'],\
  19. ca_certs=self.connectionConfig['SSL']['ca'])
  20. #password=self.connectionConfig['SSL']['keyPwd'],\ doesnt work until 1.25
  21. def getBasicAuth(self):
  22. user=self.connectionConfig['orthanc']['user']
  23. pwd=self.connectionConfig['orthanc']['password']
  24. return user+":"+pwd
  25. def getCoreURL(self):
  26. return self.connectionConfig['orthanc']['server']
  27. def get(self,url,binary=False):
  28. debug=False
  29. if debug:
  30. print("GET: {0}").format(url)
  31. print("as {0}").format(user)
  32. headers=urllib3.util.make_headers(basic_auth=self.getBasicAuth())
  33. try:
  34. if not binary:
  35. return self.http.request('GET',url,headers=headers)
  36. else:
  37. return self.http.request('GET',url,headers=headers,preload_content=False)
  38. #f contains json as a return value
  39. except urllib3.exceptions.HTTPError as e:
  40. print(e)
  41. def post(self,url,dataType,data):
  42. #dataType is typically json or octet-stream
  43. debug=False
  44. headers=urllib3.util.make_headers(basic_auth=self.getBasicAuth())
  45. headers['Content-Type']="application/"+dataType#for files
  46. #add csrf;also sets self.cookie
  47. #headers["X-LABKEY-CSRF"]=self.getCSRF()
  48. #doesn't seem like orthanc is big on security
  49. #headers["Cookie"]=self.cookie
  50. try:
  51. return self.http.request('POST',url,headers=headers,body=data)
  52. #f contains json as a return value
  53. except urllib3.exceptions.HTTPError as e:
  54. print(e)
  55. def put(self,url,data):
  56. debug=False
  57. if debug:
  58. print("PUT: {}").format(url)
  59. headers=urllib3.util.make_headers(basic_auth=self.getBasicAuth())
  60. headers["Content-Type"]="application/octet-stream"
  61. #add csrf
  62. #headers["X-LABKEY-CSRF"]=self.getCSRF()
  63. #headers["Cookie"]=self.cookie
  64. try:
  65. return self.http.request('PUT',url,headers=headers,body=data)
  66. #f contains json as a return value
  67. except urllib3.exceptions.HTTPError as e:
  68. print(e)