Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

Python/Requests: Correct login returns 401 unauthorized

I have a python application logs in to a remote host via basic HTTP authentication. Authentication is as follows:

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)

This error is printed:

401 Client Error: Unauthorized for url

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...