labkeyInterface.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import urllib3
  2. #requests doesnt work as it lacks key password checking
  3. import json
  4. class labkeyInterface:
  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 GetLabkeyUrl(self):
  22. return self.connectionConfig['host']+"/labkey"
  23. def GetLabkeyWebdavUrl(self):
  24. return self.GetLabkeyUrl()+"/_webdav"
  25. def getBasicAuth(self):
  26. user=self.connectionConfig['labkey']['user']
  27. pwd=self.connectionConfig['labkey']['password']
  28. return user+":"+pwd
  29. def get(self,url):
  30. debug=False
  31. if debug:
  32. print("GET: {0}").format(url)
  33. print("as {0}").format(user)
  34. headers=urllib3.util.make_headers(basic_auth=self.getBasicAuth())
  35. try:
  36. return self.http.request('GET',url,headers=headers)
  37. #f contains json as a return value
  38. except urllib3.exceptions.HTTPError as e:
  39. print(e)
  40. def post(self,url,data):
  41. debug=False
  42. headers=urllib3.util.make_headers(basic_auth=self.getBasicAuth())
  43. headers["Content-Type"]="application/json"
  44. #add csrf;also sets self.cookie
  45. headers["X-LABKEY-CSRF"]=self.getCSRF()
  46. headers["Cookie"]=self.cookie
  47. try:
  48. return self.http.request('POST',url,headers=headers,body=data)
  49. #f contains json as a return value
  50. except urllib3.exceptions.HTTPError as e:
  51. print(e)
  52. def put(self,url,data):
  53. debug=False
  54. if debug:
  55. print("PUT: {}").format(url)
  56. headers=urllib3.util.make_headers(basic_auth=self.getBasicAuth())
  57. headers["Content-Type"]="application/octet-stream"
  58. #add csrf
  59. headers["X-LABKEY-CSRF"]=self.getCSRF()
  60. headers["Cookie"]=self.cookie
  61. try:
  62. return self.http.request('PUT',url,headers=headers,body=data)
  63. #f contains json as a return value
  64. except urllib3.exceptions.HTTPError as e:
  65. print(e)
  66. def getCSRF(self):
  67. url=self.GetLabkeyUrl()+'/login/whoAmI.view'
  68. response=self.get(url)
  69. self.cookie=response.getheader('Set-Cookie')
  70. jsonData=json.loads(response.data)
  71. return jsonData["CSRF"]