简体   繁体   English

Python /请求:正确的登录返回未经授权的401

[英]Python/Requests: Correct login returns 401 unauthorized

I have a python application logs in to a remote host via basic HTTP authentication. 我有一个python应用程序通过基本的HTTP身份验证登录到远程主机。 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. 我不是python忍者。 Any clues ? 有什么线索吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM