Python - urllib2 how to know if our authorization is successful
Question: When you would normally login to a website we can use urllib2.Request as so.

    
    
    import urllib2, base64
    req = urllib2.Request("http://www.facebook.com/")
    base64string = base64.encodestring("%s:%s" % ("username", "password")).replace("\n", "")
    req.add_header("Authorization", "Basic %s" % base64string)
    requested = urllib2.urlopen(req)
    

But how do we know if the authorization was successful? Because you could of
just opened a URL of a wrong authorization.


Answer: A `urllib2.HTTPError` exception is raised when you are not authorised and a
401 status is returned:

    
    
    >>> import urllib2, base64
    >>> req = urllib2.Request('http://httpbin.org/basic-auth/foouser/barpw')
    >>> base64string = base64.encodestring("%s:%s" % ("username", "password")).replace("\n", "")
    >>> req.add_header("Authorization", "Basic %s" % base64string)
    >>> urllib2.urlopen(req)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 127, in urlopen
        return _opener.open(url, data, timeout)
      File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 410, in open
        response = meth(req, response)
      File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 523, in http_response
        'http', request, response, code, msg, hdrs)
      File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 448, in error
        return self._call_chain(*args)
      File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 382, in _call_chain
        result = func(*args)
      File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 531, in http_error_default
        raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
    urllib2.HTTPError: HTTP Error 401: UNAUTHORIZED
    

On successful authorisation you'll get a response object instead:

    
    
    >>> req = urllib2.Request('http://httpbin.org/basic-auth/foouser/barpw')
    >>> base64string = base64.encodestring("%s:%s" % ("foouser", "barpw")).replace("\n", "")
    >>> req.add_header("Authorization", "Basic %s" % base64string)
    >>> response = urllib2.urlopen(req)
    >>> response.getcode()
    200
    

