Trap Authentication Errors in HTTP Request

naugiedoggie michael.a.powe at gmail.com
Fri Sep 10 18:09:15 CEST 2010


Hello,

I have a script that authenticates to a web service provider to
retrieve data.  This script provides an authentication header built in
a very basic way like this:

<code>
# Creates an authentication object with the credentials for a given
URL
def createPasswordManager(headers) :
    passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm()
 
passwordManager.add_password(None,overview_url,headers[0],headers[1])
    return passwordManager

# Creates an authentication handler for the authentication object
created above
def createAuthenticationHandler(passwordManager) :
    authenticationHandler =
urllib2.HTTPBasicAuthHandler(passwordManager)
    return authenticationHandler

# Creates an opener that sets the credentials in the Request
def createOpener(authHandler) :
    return urllib2.build_opener(authHandler)
</code>

This script makes multiple calls for data.  I would like to trap an
exception for authentication failure so that it doesn't go through its
entire list of calls when there's a problem with the login.  The
assumption is that if there is a login failure, the script is using
incorrect authentication information.

I have the call for data retrieval wrapped in try/except, to catch
HTTPError, but apparently no '401' is explicitly thrown when
authentication fails.  And I don't see an explicit Exception that is
thrown in urllib2 for handling these failures.

How can I achieve my goal of trapping these exceptions and exiting
cleanly?

Thanks.

mp



More information about the Python-list mailing list