pythonpython-3.xhp-quality-center

Python: passing url through variable not working


I've below code in python to connect to HP QC ALM and it's working as expected when values are hardcoded:

from win32com.client import Dispatch
class QC_ConnectorClass(object):
def __init__(self):
    print("class init")

def ConnectToQC(self):
    #HP QC OTA methods
    self.TD = Dispatch("TDApiOle80.TDConnection.1")
    self.TD.InitConnectionEx("http://hpqcurl.org")
    self.TD.Login("UName","Pwd")
    self.TD.Connect("Domain","project")
    if self.TD.Connected == True:
        print("Logged in")
        self.TD.Logout();
        print("Logged out")
        self.TD.ReleaseConnection();
    else:
        print("Login failed")

On passing hp qc url to variable like

hpQCURL="http://hpqcurl.org" 

and pass the variable like this:

self.TD.InitConnectionEx(hpQCURL)

I receive the following error:

File "<COMObject TDApiOle80.TDConnection.1>", line 2, in InitConnectionEx
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147023174), None)

Solution

  • from win32com.client import Dispatch
    class QC_ConnectorClass(object):
        var = "http://hpqcurl.org"
        def __init__(self):
            print("class init")    
        def ConnectToQC(self):
            #HP QC OTA methods
            self.TD = Dispatch("TDApiOle80.TDConnection.1")
            self.TD.InitConnectionEx(QC_ConnectorClass.var)
            self.TD.Login("UName","Pwd")
            self.TD.Connect("Domain","project")
            if self.TD.Connected == True:
                print("Logged in")
                self.TD.Logout();
                print("Logged out")
                self.TD.ReleaseConnection();
            else:
                print("Login failed")
    

    Worked for me, but you can also initialize the variable globally outside the scope of the class. In this case I defined a static variable, that's why I need to call it in this way: QC_ConnectorClass.var But take a look on this answer to understand the importance of the position of the initialization (correct way to define class variables in Python)