Python/Requests: Correct login returns 401 unauthorized
<p>I have a python application logs in to a remote host via basic HTTP authentication. 
Authentication is as follows: </p>

<pre><code>def make_authenticated_request(host, username, password):
    url = host
    r = requests.get(url, auth=(username, password))
    r.raise_for_status()
    return r

test = Looter.make_authenticated_request("http://" + host + "/status/status_deviceinfo.htm", user, password)
</code></pre>

<p>This error is printed:  </p>

<p><code>401 Client Error: Unauthorized for url</code>  </p>

<p>Strange thing is that this doesn't always happen. It randomly fails/succeeds, for the same host with the same credentials. </p>

<p>Login is however correct, and works flawlessly in my browser. I'm no python ninja. Any clues ?</p>

<p>I might rewrite it to look something like this.. change it around however you need or like.  The point here is that i'm using a session and passing it around to make another requests.  You can reuse that session object to make other requests.  Now if you making lots of requests an authing in each time like your code suggests.  The site could be locking you out, which is why a session works better because you don't have to continue to auth in.</p>

<pre><code>import requests

class Looter(object):
  def __init__(self):
    self.s = None

  def create_session(self, url, username, password):
    # create a Session
    s = requests.Session()
    # auth in
    res = s.get(url, auth=(username, password))
    if res.status_code == 200:
      self.s = s

  def make_request(self, url):
    self.s.get(url)
    #do something with the requests

l = Looter()
l.create_session(url, username, password)
# print the session to see if it authed in
print l.s.status_code
</code></pre>

python python-requests