Selaa lähdekoodia

Adding print brackets for 3.7 compatibility. Adding error handler in post to print error as error 400 is related to bad database access.

Andrej Studen @ Win7 6 vuotta sitten
vanhempi
commit
7212758e9e

+ 6 - 6
labkeySlicerPythonExtension/fileIO.py

@@ -61,11 +61,11 @@ class remoteFileSelector(qt.QMainWindow):
 
 
     def onFileListDoubleClicked(self,item):
     def onFileListDoubleClicked(self,item):
         if item == None:
         if item == None:
-            print "Selected items: None"
+            print("Selected items: None")
             return
             return
 
 
         iText=item.text()
         iText=item.text()
-        print "Selected items: {0} ".format(iText)
+        print ("Selected items: {0} ").format(iText)
 
 
 
 
         #this is hard -> compose path string from currentRemoteDir and selection
         #this is hard -> compose path string from currentRemoteDir and selection
@@ -83,11 +83,11 @@ class remoteFileSelector(qt.QMainWindow):
                 self.currentRemoteDir+='/'
                 self.currentRemoteDir+='/'
             self.currentRemoteDir+=item.text()
             self.currentRemoteDir+=item.text()
 
 
-        print "Listing {0}".format(self.currentRemoteDir)
+        print ("Listing {0}").format(self.currentRemoteDir)
         flist=self.master.network.toRelativePath(
         flist=self.master.network.toRelativePath(
             self.master.network.listDir(self.currentRemoteDir))
             self.master.network.listDir(self.currentRemoteDir))
-        print "Got"
-        print flist
+        print ("Got")
+        print (flist)
         flist.insert(0,'..')
         flist.insert(0,'..')
         flist.insert(0,'.')
         flist.insert(0,'.')
         self.populateFileList(flist)
         self.populateFileList(flist)
@@ -200,7 +200,7 @@ class fileIOWidget(slicer.ScriptedLoadableModule.ScriptedLoadableModuleWidget):
     def copyLocalToRemote(self,localPath,remotePath):
     def copyLocalToRemote(self,localPath,remotePath):
         if os.path.isfile(localPath):
         if os.path.isfile(localPath):
             #end recursion
             #end recursion
-            print "Copy {} to {}".format(localPath,remotePath)
+            print ("Copy {} to {}").format(localPath,remotePath)
             self.network.copyFileToRemote(localPath,remotePath)
             self.network.copyFileToRemote(localPath,remotePath)
             return
             return
 
 

+ 17 - 17
labkeySlicerPythonExtension/labkeySlicerPythonExtension.py

@@ -184,21 +184,21 @@ class labkeySlicerPythonExtensionWidget(ScriptedLoadableModuleWidget):
      #pwd=qt.QInputDialog.getText(None,'Certificate password',
      #pwd=qt.QInputDialog.getText(None,'Certificate password',
      # 'Enter certificate password',qt.QLineEdit.Password)
      # 'Enter certificate password',qt.QLineEdit.Password)
      if not(filename) :
      if not(filename) :
-         print "No file selected"
+         print("No file selected")
          return
          return
 
 
      f=qt.QFile(filename)
      f=qt.QFile(filename)
      if not (f.open(qt.QIODevice.ReadOnly)) :
      if not (f.open(qt.QIODevice.ReadOnly)) :
-         print "Could not open file"
+         print("Could not open file")
          return
          return
 
 
      certList=qt.QSslCertificate.fromPath(filename)
      certList=qt.QSslCertificate.fromPath(filename)
      if len(certList) < 1:
      if len(certList) < 1:
-         print "Troubles parsing {0}".format(filename)
+         print ("Troubles parsing {0}").format(filename)
          return
          return
 
 
      self.logic.cert=qt.QSslCertificate(f)
      self.logic.cert=qt.QSslCertificate(f)
-     print "cert.isNull()={0}".format(self.logic.cert.isNull())
+     print("cert.isNull()={0}").format(self.logic.cert.isNull())
      self.userCertButton.setText(filename)
      self.userCertButton.setText(filename)
      self.authName.setText(self.logic.cert.subjectInfo("emailAddress"))
      self.authName.setText(self.logic.cert.subjectInfo("emailAddress"))
 
 
@@ -206,12 +206,12 @@ class labkeySlicerPythonExtensionWidget(ScriptedLoadableModuleWidget):
       filename=qt.QFileDialog.getOpenFileName(None,'Open private key',
       filename=qt.QFileDialog.getOpenFileName(None,'Open private key',
             self.startDir, '*.key')
             self.startDir, '*.key')
       if not (filename) :
       if not (filename) :
-          print "No file selected"
+          print ("No file selected")
           return
           return
 
 
       f=qt.QFile(filename)
       f=qt.QFile(filename)
       if not (f.open(qt.QIODevice.ReadOnly)) :
       if not (f.open(qt.QIODevice.ReadOnly)) :
-          print "Could not open file"
+          print ("Could not open file")
           return
           return
       self.pwd=qt.QInputDialog.getText(None,'Private key password',
       self.pwd=qt.QInputDialog.getText(None,'Private key password',
         'Enter key password',qt.QLineEdit.Password)
         'Enter key password',qt.QLineEdit.Password)
@@ -224,19 +224,19 @@ class labkeySlicerPythonExtensionWidget(ScriptedLoadableModuleWidget):
       filename=qt.QFileDialog.getOpenFileName(None,'Open authority certificate',
       filename=qt.QFileDialog.getOpenFileName(None,'Open authority certificate',
                self.startDir, '*.crt')
                self.startDir, '*.crt')
       if not(filename) :
       if not(filename) :
-         print "No file selected"
+         print("No file selected")
          return
          return
 
 
       f=qt.QFile(filename)
       f=qt.QFile(filename)
 
 
       if not (f.open(qt.QIODevice.ReadOnly)) :
       if not (f.open(qt.QIODevice.ReadOnly)) :
-          print "Could not open file"
+          print("Could not open file")
           return
           return
 
 
       certList=qt.QSslCertificate.fromPath(filename)
       certList=qt.QSslCertificate.fromPath(filename)
 
 
       if len(certList) < 1:
       if len(certList) < 1:
-          print "Troubles parsing {0}".format(filename)
+          print("Troubles parsing {0}").format(filename)
           return
           return
       self.logic.caCert=qt.QSslCertificate(f)#certList[0]
       self.logic.caCert=qt.QSslCertificate(f)#certList[0]
       self.caCertButton.setText(filename)
       self.caCertButton.setText(filename)
@@ -284,23 +284,23 @@ class labkeySlicerPythonExtensionWidget(ScriptedLoadableModuleWidget):
 
 
   def updateAuthName(self,txt):
   def updateAuthName(self,txt):
       self.network.auth_name=txt
       self.network.auth_name=txt
-      print "Setting username to {0}".format(self.network.auth_name);
+      print("Setting username to {0}").format(self.network.auth_name);
 
 
   def updateAuthPass(self,txt):
   def updateAuthPass(self,txt):
       self.network.auth_pass=txt
       self.network.auth_pass=txt
-      print "Setting password."
+      print("Setting password.")
 
 
   def updateServerURL(self,txt):
   def updateServerURL(self,txt):
       self.network.hostname=txt
       self.network.hostname=txt
-      print "Setting hostname to {0}".format(self.network.hostname);
+      print("Setting hostname to {0}").format(self.network.hostname);
 
 
   def onFileListDoubleClicked(self,item):
   def onFileListDoubleClicked(self,item):
         if item == None:
         if item == None:
-            print "Selected items: None"
+            print("Selected items: None")
             return
             return
 
 
         iText=item.text()
         iText=item.text()
-        print "Selected items: {0} ".format(iText)
+        print("Selected items: {0} ").format(iText)
 
 
 
 
         #this is hard -> compose path string from currentRemoteDir and selection
         #this is hard -> compose path string from currentRemoteDir and selection
@@ -317,11 +317,11 @@ class labkeySlicerPythonExtensionWidget(ScriptedLoadableModuleWidget):
             if len(self.currentRemoteDir)>0:
             if len(self.currentRemoteDir)>0:
                 self.currentRemoteDir+='/'
                 self.currentRemoteDir+='/'
             self.currentRemoteDir+=item.text()
             self.currentRemoteDir+=item.text()
-        print "Listing {0}".format(self.currentRemoteDir)
+        print("Listing {0}").format(self.currentRemoteDir)
         flist=self.network.toRelativePath(
         flist=self.network.toRelativePath(
             self.network.listDir(self.currentRemoteDir))
             self.network.listDir(self.currentRemoteDir))
-        print "Got"
-        print flist
+        print("Got")
+        print(flist)
         flist.insert(0,'..')
         flist.insert(0,'..')
         flist.insert(0,'.')
         flist.insert(0,'.')
         self.populateFileList(flist)
         self.populateFileList(flist)

+ 3 - 2
labkeySlicerPythonExtension/loadDicom.py

@@ -4,8 +4,9 @@ import subprocess
 import re
 import re
 
 
 dicomModify=os.getenv("HOME")
 dicomModify=os.getenv("HOME")
-dicomModify+="/software/install/"
-dicomModify+="dicomModify/bin/dicomModify"
+if not dicomModify==None:
+    dicomModify+="/software/install/"
+    dicomModify+="dicomModify/bin/dicomModify"
 
 
 class loadDicom(slicer.ScriptedLoadableModule.ScriptedLoadableModule):
 class loadDicom(slicer.ScriptedLoadableModule.ScriptedLoadableModule):
     def __init__(self,parent):
     def __init__(self,parent):

+ 35 - 30
labkeySlicerPythonExtension/slicerNetwork.py

@@ -39,10 +39,10 @@ class labkeyURIHandler(slicer.vtkURIHandler):
         self.className="labkeyURIHandler"
         self.className="labkeyURIHandler"
         slicer.mrmlScene.AddURIHandler(self)
         slicer.mrmlScene.AddURIHandler(self)
         try:
         try:
-	       fhome=os.environ["HOME"]
+            fhome=os.environ["HOME"]
         except:
         except:
-	    #in windows, the variable is called HOMEPATH
-	       fhome=os.environ['HOMEDRIVE']+os.environ['HOMEPATH']
+	           #in windows, the variable is called HOMEPATH
+            fhome=os.environ['HOMEDRIVE']+os.environ['HOMEPATH']
 
 
         self.localCacheDirectory=os.path.join(fhome,"labkeyCache")
         self.localCacheDirectory=os.path.join(fhome,"labkeyCache")
         self.configDir=os.path.join(fhome,".labkey")
         self.configDir=os.path.join(fhome,".labkey")
@@ -52,7 +52,7 @@ class labkeyURIHandler(slicer.vtkURIHandler):
 
 
 
 
     def CanHandleURI(self,uri):
     def CanHandleURI(self,uri):
-        print "labkeyURIHandler::CanHandleURI({0})".format(uri)
+        print("labkeyURIHandler::CanHandleURI({0})").format(uri)
         if uri.find('labkey://')==0:
         if uri.find('labkey://')==0:
             return 1
             return 1
         return 0
         return 0
@@ -83,7 +83,7 @@ class labkeyURIHandler(slicer.vtkURIHandler):
         relativePath=re.sub('labkey://','',source)
         relativePath=re.sub('labkey://','',source)
         sp=os.sep.encode('string-escape')
         sp=os.sep.encode('string-escape')
         if debug:
         if debug:
-            print "Substituting / with {0} in {1}".format(sp,relativePath)
+            print("Substituting / with {0} in {1}").format(sp,relativePath)
         relativePath=re.sub('/',sp,relativePath)
         relativePath=re.sub('/',sp,relativePath)
         return os.path.join(self.localCacheDirectory,relativePath)
         return os.path.join(self.localCacheDirectory,relativePath)
 
 
@@ -93,7 +93,7 @@ class labkeyURIHandler(slicer.vtkURIHandler):
     def GetLabkeyPathFromLocalPath(self,f):
     def GetLabkeyPathFromLocalPath(self,f):
         #report it with URL separator, forward-slash
         #report it with URL separator, forward-slash
         if f.find(self.localCacheDirectory)<-1:
         if f.find(self.localCacheDirectory)<-1:
-            print "Localpath misformation. Exiting"
+            print("Localpath misformation. Exiting")
             return "NULL"
             return "NULL"
         dest=re.sub(self.localCacheDirectory,'',f)
         dest=re.sub(self.localCacheDirectory,'',f)
         #leaves /ContextPath/%40files/subdirectory_list/files
         #leaves /ContextPath/%40files/subdirectory_list/files
@@ -124,7 +124,7 @@ class labkeyURIHandler(slicer.vtkURIHandler):
     def StageFileRead(self,source,dest):
     def StageFileRead(self,source,dest):
         debug=False
         debug=False
         if debug:
         if debug:
-            print "labkeyURIHandler::StageFileRead({0},{1})".format(source,dest)
+            print("labkeyURIHandler::StageFileRead({0},{1})").format(source,dest)
         labkeyPath=re.sub('labkey://','',source)
         labkeyPath=re.sub('labkey://','',source)
         remote=self.readFile(self.hostname,labkeyPath)
         remote=self.readFile(self.hostname,labkeyPath)
         #make all necessary directories
         #make all necessary directories
@@ -139,16 +139,16 @@ class labkeyURIHandler(slicer.vtkURIHandler):
         if debug:
         if debug:
 	         remote.seek(0,2)
 	         remote.seek(0,2)
 	         sz=remote.tell()
 	         sz=remote.tell()
-	         print "Remote size: {0}".format(sz)
+	         print("Remote size: {0}").format(sz)
 
 
         remote.seek(0)
         remote.seek(0)
         shutil.copyfileobj(remote,local)
         shutil.copyfileobj(remote,local)
         if debug:
         if debug:
-	         print "Local size: {0}".format(local.tell())
+	         print("Local size: {0}").format(local.tell())
         local.close()
         local.close()
 
 
     def StageFileWrite(self,source,dest):
     def StageFileWrite(self,source,dest):
-        print "labkeyURIHandler::StageFileWrite({0},{1}) not implemented yet".format(
+        print("labkeyURIHandler::StageFileWrite({0},{1}) not implemented yet").format(
             source,dest)
             source,dest)
 
 
     def fileTypesAvailable(self):
     def fileTypesAvailable(self):
@@ -188,7 +188,7 @@ class labkeyURIHandler(slicer.vtkURIHandler):
             self.ctx.verify_mode=ssl.CERT_REQUIRED
             self.ctx.verify_mode=ssl.CERT_REQUIRED
             self.ctx.load_verify_locations(cacert)
             self.ctx.load_verify_locations(cacert)
         except ssl.SSLError as err:
         except ssl.SSLError as err:
-            print " Failed to configure SSL: {0}".format(str(err))
+            print(" Failed to configure SSL: {0}").format(str(err))
         self.mode="https"
         self.mode="https"
 
 
 
 
@@ -203,7 +203,7 @@ class labkeyURIHandler(slicer.vtkURIHandler):
         self.opener=urllib2.build_opener(http_handler,cookie_handler)
         self.opener=urllib2.build_opener(http_handler,cookie_handler)
 
 
     def initFromConfig(self):
     def initFromConfig(self):
-        path=os.path.join(self.configDir,"remote.json")
+        path=os.path.join(self.configDir,"Remote.json")
         try:
         try:
             self.parseConfig(path)
             self.parseConfig(path)
         except OSError:
         except OSError:
@@ -214,7 +214,7 @@ class labkeyURIHandler(slicer.vtkURIHandler):
         try:
         try:
             f=open(fname)
             f=open(fname)
         except OSError as e:
         except OSError as e:
-            print "Confgiuration error: OS error({0}): {1}".format(e.errno, e.strerror)
+            print("Confgiuration error: OS error({0}): {1}").format(e.errno, e.strerror)
             raise
             raise
 
 
         dt=json.load(f)
         dt=json.load(f)
@@ -237,8 +237,8 @@ class labkeyURIHandler(slicer.vtkURIHandler):
 
 
         debug=False
         debug=False
         if debug:
         if debug:
-            print "GET: {0}".format(url)
-            print "as {0}".format(self.auth_name)
+            print("GET: {0}").format(url)
+            print("as {0}").format(self.auth_name)
         r=urllib2.Request(url)
         r=urllib2.Request(url)
         base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
         base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
         r.add_header("Authorization", "Basic %s" % base64string)
         r.add_header("Authorization", "Basic %s" % base64string)
@@ -257,15 +257,20 @@ class labkeyURIHandler(slicer.vtkURIHandler):
 
 
         base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
         base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
         r.add_header("Authorization", "Basic %s" % base64string)
         r.add_header("Authorization", "Basic %s" % base64string)
-        print "{}: {}".format(r.get_method(),r.get_full_url())
-        print "data: {}".format(r.get_data())
-        print "Content-Type: {}".format(r.get_header('Content-Type'))
-        return self.opener.open(r)
+        print("{}: {}").format(r.get_method(),r.get_full_url())
+        print("data: {}").format(r.get_data())
+        print("Content-Type: {}").format(r.get_header('Content-Type'))
+        try:
+            return self.opener.open(r)
+        except urllib2.HTTPError as e:
+            print e.code
+            print e.read()
+            return e
         #f contains json as a return value
         #f contains json as a return value
 
 
     def put(self,url,data):
     def put(self,url,data):
 
 
-        print "PUT: {0}".format(url)
+        print("PUT: {0}").format(url)
         r=MethodRequest(url.encode('utf-8'),method="PUT")
         r=MethodRequest(url.encode('utf-8'),method="PUT")
         #makes it a post
         #makes it a post
         r.add_data(data)
         r.add_data(data)
@@ -295,7 +300,7 @@ class labkeyURIHandler(slicer.vtkURIHandler):
         try:
         try:
             f=self.opener.open(r)
             f=self.opener.open(r)
         except:
         except:
-            print "Error: Failed MKCOL {}".format(remoteDir)
+            print("Error: Failed MKCOL {}").format(remoteDir)
             return False
             return False
         return True
         return True
 
 
@@ -324,12 +329,12 @@ class labkeyURIHandler(slicer.vtkURIHandler):
         try:
         try:
             f=self.opener.open(r)
             f=self.opener.open(r)
         except:
         except:
-            print "Error: Failed DELETE {}".format(remoteDir)
+            print("Error: Failed DELETE {}").format(remoteDir)
             return False
             return False
         return True
         return True
 
 
     def listDir(self,dir):
     def listDir(self,dir):
-        print "Listing for {0}".format(dir)
+        print("Listing for {0}").format(dir)
         dirUrl=self.GetLabkeyWebdavUrl()+"/"+dir
         dirUrl=self.GetLabkeyWebdavUrl()+"/"+dir
         status,dirs=self.listRemoteDir(dirUrl)
         status,dirs=self.listRemoteDir(dirUrl)
         return dirs
         return dirs
@@ -349,7 +354,7 @@ class labkeyURIHandler(slicer.vtkURIHandler):
         r.add_data(PROPFIND)
         r.add_data(PROPFIND)
         base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
         base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
         r.add_header("Authorization", "Basic %s" % base64string)
         r.add_header("Authorization", "Basic %s" % base64string)
-        print "PROPFIND: {0}".format(remotePath)
+        print("PROPFIND: {0}").format(remotePath)
         try:
         try:
             f=self.opener.open(r)
             f=self.opener.open(r)
         except:
         except:
@@ -380,7 +385,7 @@ class labkeyURIHandler(slicer.vtkURIHandler):
         r.add_data(PROPFIND)
         r.add_data(PROPFIND)
         base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
         base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
         r.add_header("Authorization", "Basic %s" % base64string)
         r.add_header("Authorization", "Basic %s" % base64string)
-        print "PROPFIND: {0}".format(dirUrl)
+        print("PROPFIND: {0}").format(dirUrl)
         dirs=[]
         dirs=[]
         try:
         try:
             f=self.opener.open(r)
             f=self.opener.open(r)
@@ -417,14 +422,14 @@ class labkeyURIHandler(slicer.vtkURIHandler):
         if labkeyPath=="NULL":
         if labkeyPath=="NULL":
             errorCode="Failed to upload {}. Potential incorrect location"
             errorCode="Failed to upload {}. Potential incorrect location"
             errorCode+=". Should be in labkeyCache!"
             errorCode+=". Should be in labkeyCache!"
-            print errorCode.format(localPath)
+            print(errorCode.format(localPath))
             return False
             return False
         labkeyDir=labkeyPath[0:labkeyPath.rfind('/')]
         labkeyDir=labkeyPath[0:labkeyPath.rfind('/')]
         remoteDir=self.GetLabkeyWebdavUrl()+'/'+labkeyDir
         remoteDir=self.GetLabkeyWebdavUrl()+'/'+labkeyDir
         if not self.remoteDirExists(remoteDir):
         if not self.remoteDirExists(remoteDir):
             if not self.mkdirs(remoteDir):
             if not self.mkdirs(remoteDir):
                 errorCode="UploadFile: Could not create directory {}"
                 errorCode="UploadFile: Could not create directory {}"
-                print errorCode.format(remoteDir)
+                print(errorCode.format(remoteDir))
                 return False
                 return False
 
 
         #make an URL request
         #make an URL request
@@ -440,7 +445,7 @@ class labkeyURIHandler(slicer.vtkURIHandler):
         if not self.remoteDirExists(labkeyDir):
         if not self.remoteDirExists(labkeyDir):
             if not self.mkdirs(labkeyDir):
             if not self.mkdirs(labkeyDir):
                 errorCode="UploadFile: Could not create directory {}"
                 errorCode="UploadFile: Could not create directory {}"
-                print errorCode.format(labkeyDir)
+                print(errorCode.format(labkeyDir))
                 return False
                 return False
 
 
         #make an URL request
         #make an URL request
@@ -461,7 +466,7 @@ class labkeyURIHandler(slicer.vtkURIHandler):
                 fdir=os.path.dirname(self.GetFile(f))
                 fdir=os.path.dirname(self.GetFile(f))
             except:
             except:
                 #fails if there is a subdirectory; go recursively
                 #fails if there is a subdirectory; go recursively
-                print "self.readDir(f) not implemented"
+                print("self.readDir(f) not implemented")
         return fdir
         return fdir
 
 
     def loadDataset(self,project,dataset):
     def loadDataset(self,project,dataset):
@@ -475,7 +480,7 @@ class labkeyURIHandler(slicer.vtkURIHandler):
         url+='/query-selectRows.api?schemaName=study&query.queryName='+dataset
         url+='/query-selectRows.api?schemaName=study&query.queryName='+dataset
         url+="&query."+variable+"~"+oper+"="+value
         url+="&query."+variable+"~"+oper+"="+value
         if debug:
         if debug:
-            print "Sending {}".format(url)
+            print("Sending {}").format(url)
         return json.load(self.get(url))
         return json.load(self.get(url))