Python - HTTP Digest Authentication with urllib2

2

I needed to authenticate on a test server to consume a service in a webservice, I was able to make the authentication and generate the xml with the following code based on a code SOen

operacao = 'consulta'
Agencia = "X"
Agente = "X"
Origem = 1
Destino = 2
Data = 2014-06-17

params = '?operacao=%s&agencia=%s&agente=%s&origem=%s&destino=destino&data=%s&idtransacao=c2153663a6a6a8733f58b8c79&fpag=J0' %(operacao, Agencia, Agente, Origem, Destino, Data)

oPass = urllib2.HTTPPasswordMgrWithDefaultRealm()
oPass.add_password(None, Url, User, Password)

authHandler = urllib2.HTTPDigestAuthHandler(oPass)
opener = urllib2.build_opener(authHandler)

resposta = opener.open("%s%s" %(Url, params)) #Retorna um XML
print resposta.read() #Leitura do XML
resposta.close() 

I've been studying the urllib2 library to understand classes and methods: HTTPPasswordMgrWithDefaultRealm , add_password , HTTPDigestAuthHandler , build_opener .

I'm reading the python documentation , but it was not clear to me the function of each of these methods in the code I am using, I would like a clearer explanation of the function of these classes and methods that I'm using in the code.

    
asked by anonymous 16.06.2014 / 19:39

1 answer

1

So far I've come up with the following answer:

Creating a password manager, causes user and password to be used as authentication elements:

oPass = urllib2.HTTPPasswordMgrWithDefaultRealm()

Adding Authentication Elements to the manager:

oPass.add_password(None, Url, User, Password)

Creating a handler for passwords (What I understood by handler is that this would be a "handler" of authentication.):

authHandler = urllib2.HTTPDigestAuthHandler(oPass)

Create an opener:

opener = urllib2.build_opener(authHandler)

Use the opener to fetch a URL // Return the XML from the requested service

resposta = opener.open("%s%s" %(Url, params))

Reading and displaying XML:

print resposta.read()

Close the connection:

resposta.close()
    
20.06.2014 / 19:10