Trap Authentication Errors in HTTP Request

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


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:

# Creates an authentication object with the credentials for a given
def createPasswordManager(headers) :
    passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm()
    return passwordManager

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

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

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



More information about the Python-list mailing list