Strange behavior of urllib2.HTTPHTTPBasicAuthHandler when handling 401 Authorization?
<p>The server I'm trying to logon and download a file from  is using Basic Auth as I can confirm from Chrome Dev Tools and some tests. So I write code like below, bad example of OOP perhaps, but should make sense.</p>

<pre><code>class Utils(object):
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.top_level_url = 'http://test.com/'
        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
        password_mgr.add_password(None, self.top_level_url, self.username, self.password)
        basic_auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr)
        opener = urllib2.build_opener(basi_auth_handler)
        urllib2.install_opener(opener)

    def download(self, filename):
        url = self.top_level_url + filename
        req = urllib2.Request(url)
        try:
            response = urllib2.urlopen(req)
            return response
        except urllib2.HTTPError as e:
            print e.headers
            raise
</code></pre>

<p>Strange things happen, when I initialize a Utils object and download the file repeatedly:</p>

<pre><code>u = Utils('username', 'password')
index = 0
while 1:
    resp = u.download('file.txt')
    index += 1
    time.sleep(1)
</code></pre>

<p>The scripts works for the first 5 times of download, but at the 6th time, it would raise HTTPError 401. But if  I change the code, add the post header to include 'Authorization: Basic ***' instead of using HTTPBasicAuthHandler, it works every time... So is this something wrong with my code or the server part setup?</p>