HTTP - basic authentication example.

John J. Lee jjl at pobox.com
Sat Sep 18 10:03:53 EDT 2004


fuzzyman at gmail.com (Michael Foord) writes:
> Jaime Wyant <programmer.py at gmail.com> wrote in message news:<mailman.3402.1095338985.5135.python-list at python.org>...
[...]
> have found it in your docs). This means I have a ClientCookie handler
> handling all my http requests.... I wonder if I can use an AuthHandler
> as well ? There will be situations where I am likely to want to add an
> Authroize header *and* handle cookies - ClientCookie manages all the
> cookies in a way that I couldn't do manually.

Sure, cookielib.HTTPCookieProcessor (or
ClientCookie.HTTPCookieProcessor) should work fine with all other
urllib2 handlers.  Cookies and Basic HTTP Authentication are quite
distinct and separate in their implementation at the HTTP level.

Assuming Python 2.4 (UNTESTED -- I haven't recently had occasion to
use any auth.):

import urllib2
import cookielib
import ClientCookie  # for some more urllib2 handlers, for good measure ;-)

def build_opener(realm, uri, user, password):
    ch = cookielib.HTTPCookieProcessor()

    mgr = HTTPPasswordMgr()
    mgr.add_password(realm, uri, user, password)
    ah = urllib2.HTTPBasicAuthHandler(mgr)

    yet_more_handlers = [ClientCookie.HTTPRefreshProcessor(max_time=None),
                         ClientCookie.HTTPEquivProcessor(),
                         ClientCookie.HTTPRobotRulesProcessor(),
                         ]

    return urllib2.build_opener(ch, ah, *yet_more_handlers)

opener = build_opener('myrealm', 'http://example.com/', 'joe', 'joe')
opener.open('http://example.com/restricted.html')

[...]
> The example you gave works I think - HTTPBasicAuthHandler does have an
> add_password method, but not the find_user_password that the
> HTTPPasswordMgr has... so I can't easily check if it works properly.
> In the urllib2 docs it says that passing a password manager in is
> optional - but *nowhere* does it document that it has an add_password
> method. It may be deducable from the fact that passing in a password
> manager is optional - but surely explicit is better than implicit
> (especially where documentation is concerned).
[...]

Tested doc patches posted to the Python sf.net patch tracker are
welcome :-)


John



More information about the Python-list mailing list