Python - HTTP Digest authentication with urllib2

Asked

Viewed 297 times

2

I needed to authenticate on a test server to consume a service on a webservice, I managed to make the authentication and generate xml with the following code based on a code of 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 have been studying the library urllib2 to understand the classes and methods: HTTPPasswordMgrWithDefaultRealm, add_password, HTTPDigestAuthHandler, build_opener.

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

1 answer

1


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

Creation of a password manager, causes the 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)

Creation of a password handler (What I understood by Handler is that this would be an authentication "handler".):

authHandler = urllib2.HTTPDigestAuthHandler(oPass)

Create an opener (opener):

opener = urllib2.build_opener(authHandler)

Uses opener to search for a URL // Returns the XML of the requested service (Answer)

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

Reading and displaying XML:

print resposta.read()

Closes the connection:

resposta.close()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.