Sat, 24 Mar 2007

Python - SOAPpy and HTTP Authentication

The other week I was wanting to use a SOAP web service that was protected by http basic authentication. I could not find a way to do the authentication with SOAPpy. I looked everywhere for an example before I stumbled upon a version of the below code in an archived newsgroup post.

from SOAPpy import Config, HTTPTransport, SOAPAddress, WSDL

class myHTTPTransport(HTTPTransport):
    username = None
    passwd = None
    
    @classmethod
    def setAuthentication(cls,u,p):
        cls.username = u
        cls.passwd = p
          
    def call(self, addr, data, namespace, soapaction=None, encoding=None,
             http_proxy=None, config=Config):
        
        if not isinstance(addr, SOAPAddress):
            addr=SOAPAddress(addr, config)
            
        if self.username != None:
            addr.user = self.username+":"+self.passwd
            
        return HTTPTransport.call(self, addr, data, namespace, soapaction,
                                  encoding, http_proxy, config)
    

if __name__ == '__main__':
    wsdlFile = 'http://localhost/soap/wsdl/'
    myHTTPTransport.setAuthentication('gollum', 'myprecious')
    server = WSDL.Proxy(wsdlFile, transport=myHTTPTransport)
    print server.ApiVersion()

It works because you can specify your own transport to the WSDL.Proxy using Python's **kw feature. The original author subclassed the default transport in Client.HTTPTransport and added a static class method to supply the basic authentication.



posted: 23:09 | comments | tags: , , ,


© 2008 PlatosCave.net