我正在尝试使用 python 进行基本身份验证的 HTTPS GET。我对 python 很陌生,指南似乎使用不同的库来做事。 (http.client、httplib 和 urllib)。谁能告诉我它是怎么做的?你怎么能告诉标准库使用?
原文由 Tom Squires 发布,翻译遵循 CC BY-SA 4.0 许可协议
我正在尝试使用 python 进行基本身份验证的 HTTPS GET。我对 python 很陌生,指南似乎使用不同的库来做事。 (http.client、httplib 和 urllib)。谁能告诉我它是怎么做的?你怎么能告诉标准库使用?
原文由 Tom Squires 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 Python 的强大功能并依靠周围最好的库之一: requests
import requests
r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
print(r.text)
变量 r(请求响应)有更多您可以使用的参数。最好的办法是进入交互式解释器并使用它,和/或阅读 请求 文档。
ubuntu@hostname:/home/ubuntu$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
>>> dir(r)
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'iter_content', 'iter_lines', 'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']
>>> r.content
b'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.text
'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.status_code
200
>>> r.headers
CaseInsensitiveDict({'x-powered-by': 'Express', 'content-length': '77', 'date': 'Fri, 20 May 2016 02:06:18 GMT', 'server': 'nginx/1.6.3', 'connection': 'keep-alive', 'content-type': 'application/json; charset=utf-8'})
原文由 IvanD 发布,翻译遵循 CC BY-SA 3.0 许可协议
4 回答4.4k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
1 回答3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
1 回答4.5k 阅读✓ 已解决
1 回答3.8k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
在 Python 3 中,以下将起作用。我正在使用标准库中的较低级别的 http.client 。另请查看 rfc2617 的第 2 部分了解基本授权的详细信息。此代码不会检查证书是否有效,但会设置 https 连接。请参阅 http.client 文档以了解如何执行此操作。