Was this page helpful?

Authenticate and read entries with Python

    Table of contents
    No headers

    This example is done with the interactive Python interpreter in a shell.

    First of all, you only need to import the library urllib2.

     >>> import urllib2
    

    It's needed to handle request/responses and to provide a simple authentication handler.

    >>> passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
    >>> url = 'http://XXXXXX/@api/deki/users/authenticate'
    >>> passmgr.add_password(None, url, 'user', 'password')
    >>> authhandler = urllib2.HTTPBasicAuthHandler(passmgr)
    >>> opener = urllib2.build_opener(authhandler)
    >>> response = opener.open(url)
    

    And you are just logged in!

    >>> print response.headers
    Date: Thu, 14 Feb 2008 13:36:58 GMT
    Server: Dream-HTTPAPI/1.5.0.24178
    Response-Uri: X
    Content-Type: text/plain; charset=iso-8859-1
    Content-Length: 53
    Set-Cookie: authtoken="3_633385930180612710_8df66cac15735913a5865dc7116f48f9"; expires=Thu, 21-Feb-2008 13:36:58 GMT; Version="1"; Path=/
    Via: 1.1 X
    Connection: close
    
    

     

    For being authenticate when you keep on sending requests, you only need to add the cookie to new requests.

    >>> request = urllib2.Request('url_page')
    >>> request.add_header('Set-Cookie',response.headers['Set-Cookie'])
    >>> page = opener.open(request)
    >>> page.read()
    

     

    And you get your page.

     

    Easy, wasn't it?

     

     

    Was this page helpful?
    Tag page
    Viewing 3 of 3 comments: view all
    is it possible to do the same thing with NTLM authentication?
    Posted 12:00, 20 Jun 2008
    The first example gives a 401 error. The same username / password entered directly work. Any ideas?
    Posted 21:19, 4 Mar 2009
    Set your own life time more easy get the <a href="http://bestfinance-blog.com/topics/home-loans">home loans</a> and everything you want.
    Posted 06:07, 13 Aug 2010
    Viewing 3 of 3 comments: view all
    You must login to post a comment.

    Copyright © 2011 MindTouch, Inc. Powered by