如何在Python Requests库中使用基本HTTP身份验证?
我正在尝试在Python中使用基本的HTTP认证。我使用的是Requests库:
auth = requests.post('http://' + hostname, auth=HTTPBasicAuth(user, password))
request = requests.get('http://' + hostname + '/rest/applications')
来自auth
变量的响应:
<<class 'requests.cookies.RequestsCookieJar'>[<Cookie JSESSIONID=cb10906c6219c07f887dff5312fb for appdynamics/controller>]>
200
CaseInsensitiveDict({'content-encoding': 'gzip', 'x-powered-by': 'JSP/2.2', 'transfer-encoding': 'chunked', 'set-cookie': 'JSESSIONID=cb10906c6219c07f887dff5312fb; Path=/controller; HttpOnly', 'expires': 'Wed, 05 Nov 2014 19:03:37 GMT', 'server': 'nginx/1.1.19', 'connection': 'keep-alive', 'pragma': 'no-cache', 'cache-control': 'max-age=78000', 'date': 'Tue, 04 Nov 2014 21:23:37 GMT', 'content-type': 'text/html;charset=ISO-8859-1'})
但是当我尝试从不同的位置获取数据时,我遇到了HTTP状态401错误:
<<class 'requests.cookies.RequestsCookieJar'>[]>
401
CaseInsensitiveDict({'content-length': '1073', 'x-powered-by': 'Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.2.2 Java/Oracle Corporation/1.7)', 'expires': 'Thu, 01 Jan 1970 00:00:00 UTC', 'server': 'nginx/1.1.19', 'connection': 'keep-alive', 'pragma': 'No-cache', 'cache-control': 'no-cache', 'date': 'Tue, 04 Nov 2014 21:23:37 GMT', 'content-type': 'text/html', 'www-authenticate': 'Basic realm="controller_realm"'})
据我所理解,在第二个请求中,会话参数没有被替换。
6 个回答
0
对于 Python 2:
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request = urllib2.Request(url)
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
data = result.read()
3
下面这个对我有效
#!/usr/bin/python3
import xml.etree.ElementTree as ET
import requests
from requests.auth import HTTPBasicAuth
url = 'http://172.25.38.135:600/service/xx/users' # my URL
response = requests.get(url, auth=HTTPBasicAuth('admin', 'adminpass!'))
string_xml = response.content
tree = ET.fromstring(string_xml)
ET.dump(tree)
48
在Python3中,这变得很简单:
import requests
response = requests.get(uri, auth=(user, password))
106
这段代码是用来做某种操作的,但具体的功能可能需要根据上下文来理解。通常情况下,代码块里会包含一些指令或者函数,这些指令会告诉计算机该怎么做。
如果你看到类似于
import requests
from requests.auth import HTTPBasicAuth
res = requests.post('https://api.github.com/user', auth=HTTPBasicAuth('user', 'password'))
print(res)
这样的占位符,通常意味着这里应该有一段代码,但具体内容没有显示出来。你可以想象成是一个空白的地方,等着你去填充具体的代码。
在学习编程的时候,理解代码的结构和逻辑是很重要的。即使你现在不太明白这些代码的具体含义,慢慢来,多看多练,最终你会掌握这些知识的。
143
你需要使用一个会话对象,并在每次请求时发送认证信息。这个会话对象还会帮你记录 cookies:
session = requests.Session()
session.auth = (user, password)
auth = session.post('http://' + hostname)
response = session.get('http://' + hostname + '/rest/applications')