ole*_*sii 24 python api python-requests appdynamics
我正在尝试在python中使用基本身份验证
auth = requests.post('http://' + hostname, auth=HTTPBasicAuth(user, password))
request = requests.get('http://' + hostname + '/rest/applications')
Run Code Online (Sandbox Code Playgroud)
响应表单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'})
Run Code Online (Sandbox Code Playgroud)
但是当我试图从不同的位置获取数据时, - 我有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"'})
Run Code Online (Sandbox Code Playgroud)
据我所知 - 在第二个请求中不是替换会话参数.
Mar*_*ers 39
您需要使用会话对象并发送每个请求的身份验证.会议还将为您跟踪Cookie:
session = requests.Session()
session.auth = (user, password)
auth = session.post('http://' + hostname)
response = session.get('http://' + hostname + '/rest/applications')
Run Code Online (Sandbox Code Playgroud)
小智 24
import requests
from requests.auth import HTTPBasicAuth
res = requests.post('https://api.github.com/user', verify=False, auth=HTTPBasicAuth('user', 'password'))
print (res)
Run Code Online (Sandbox Code Playgroud)
注意:有时,我们可能会得到 SSL 错误证书验证失败,为了避免,我们可以使用 verify=False
Wyr*_*ood 23
该示例与您的代码略有不同.
>>> from requests.auth import HTTPBasicAuth
>>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
<Response [200]>
Run Code Online (Sandbox Code Playgroud)
在 Python3 中它变得容易:
import requests
response = requests.get(uri, auth=(user, password))
Run Code Online (Sandbox Code Playgroud)