HTTP Authentication

Discussion in 'Python' started by Lakshman, Apr 6, 2009.

  1. Lakshman

    Lakshman Guest

    Whats is the python urllib2 equivallent of

    curl -u username:password status="abcd" http://example.com/update.json

    I did this:

    handle = urllib2.Request(url)
    authheader = "Basic %s" % base64.encodestring('%s:%s' % (username,
    password))
    handle.add_header("Authorization", authheader)

    Is there a better / simpler way?
    Lakshman, Apr 6, 2009
    #1
    1. Advertising

  2. Lakshman wrote:
    > Whats is the python urllib2 equivallent of
    >
    > curl -u username:password status="abcd" http://example.com/update.json
    >
    > I did this:
    >
    > handle = urllib2.Request(url)
    > authheader = "Basic %s" % base64.encodestring('%s:%s' % (username,
    > password))
    > handle.add_header("Authorization", authheader)
    >
    > Is there a better / simpler way?


    Better? Yes.
    Simpler? No.

    Actually, the proper way using the urllib2 API is more code.

    When I need it some time ago, I googled and used this recipe:

    http://www.voidspace.org.uk/python/articles/urllib2.shtml#id6


    # create a password manager
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

    # Add the username and password.
    # If we knew the realm, we could use it instead of ``None``.
    top_level_url = "http://example.com/foo/"
    password_mgr.add_password(None, top_level_url, username, password)

    handler = urllib2.HTTPBasicAuthHandler(password_mgr)

    # create "opener" (OpenerDirector instance)
    opener = urllib2.build_opener(handler)

    # use the opener to fetch a URL
    opener.open(a_url)

    # Install the opener.
    # Now all calls to urllib2.urlopen use our opener.
    urllib2.install_opener(opener)

    -- Gerhard
    Gerhard Häring, Apr 6, 2009
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jiong Feng
    Replies:
    0
    Views:
    817
    Jiong Feng
    Nov 19, 2003
  2. Paul Glavich [MVP - ASP.NET]
    Replies:
    0
    Views:
    446
    Paul Glavich [MVP - ASP.NET]
    Jun 20, 2004
  3. T. Regan
    Replies:
    3
    Views:
    708
    T. Regan
    Jun 21, 2004
  4. Max
    Replies:
    2
    Views:
    1,092
  5. Nacho Nachev
    Replies:
    2
    Views:
    896
Loading...

Share This Page