[Tutor] Trapping HTTP Authentication Failure
evert.rol at gmail.com
Sat Sep 11 13:09:31 CEST 2010
>>> My script to call a web service authenticates.
>> Sorry, but where is the (full) script? I missed an attachment or (preferably) a link.
> Sorry, the verb of the sentence is "authenticates," as in, "My script
> ... authenticates."
Sorry, misread that.
Although code does help :-).
I assume the rest of the code is just the loop around the items you want to fetch, calling getData each time with a new URL.
> But I can show the authentication portion.
> 8<-------------- start -------------------->8
> # Creates an authentication object with the credentials for a given URL
> def createPasswordManager(headers) :
> passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm()
> 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)
> # Retrieves the data
> def getData(authHeaders) :
> opener = createOpener(createAuthenticationHandler(createPasswordManager(authHeaders)))
> data = opener.open(overview_url)
> return data
> 8<--------------- end ------------------------>8
> So, to restate the question, how can I trap an exception in the cases
> in which authentication fails?
> Right now, the whole script is complete and working (thanks for your
> help with my other exception-handling question). Except for the case
> of bad credentials. The use case is that the user misspells a
> username or password or puts in a wrong account information. Then, I
> don't want them to sit for 10 minutes while the script makes 30 data
> connections, retries and fails each time.
I'm not sure what you're exactly doing here, or what you're getting, but I did get curious and dug around urllib2.py. Apparently, there is a hardcoded 5 retries before the authentication really fails. So any stack trace would be the normal stack trace times 5. Not the 30 you mentioned, but annoying enough anyway (I don't see how it would fail for every element in the loop though. Once it raises an exception, the program basically ends).
I don't know why it's hard-coded that way, and not just an option with a default of 5, but that's currently how it is (maybe someone else on this list knows?).
If that's what you're finding, perhaps the quickest way is to subclass urllib2.HTTPBasicAuthHandler, and override the http_error_auth_reqed method (essentially keeping it exactly the same apart from the hard-coded 5).
Otherwise, I'm afraid I still don't know what's the problem you're having.
More information about the Tutor