首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用基本身份验证的Python、HTTPS GET

使用基本身份验证的Python、HTTPS GET
EN

Stack Overflow用户
提问于 2011-08-10 00:31:23
回答 8查看 250.5K关注 0票数 101

我正在尝试使用python进行基本身份验证的HTTPS GET。我是python的新手,指南似乎使用了不同的库来做事情。(http.client、httplib和urllib)。有谁能教我怎么做吗?你如何告诉标准库去使用呢?

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2011-08-10 02:12:58

在Python3中,以下内容将会起作用。我使用的是标准库中较低级别的http.client。有关基本授权的详细信息,请参阅rfc2617的第2节。此代码不会检查证书是否有效,但会设置一个https连接。有关如何做到这一点,请参阅http.client文档。

代码语言:javascript
运行
复制
from http.client import HTTPSConnection
from base64 import b64encode
#This sets up the https connection
c = HTTPSConnection("www.google.com")
#we need to base 64 encode it 
#and then decode it to acsii as python 3 stores it as a byte string
userAndPass = b64encode(b"username:password").decode("ascii")
headers = { 'Authorization' : 'Basic %s' %  userAndPass }
#then connect
c.request('GET', '/', headers=headers)
#get the response back
res = c.getresponse()
# at this point you could check the status etc
# this gets the page text
data = res.read()  
票数 140
EN

Stack Overflow用户

发布于 2016-05-20 10:14:03

使用Python的强大功能,并依靠周围最好的库之一:requests

代码语言:javascript
运行
复制
import requests

r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
print(r.text)

变量r(请求和响应)有更多的参数可供使用。最好的方法是进入交互式解释器,并尝试使用它,和/或阅读requests文档。

代码语言:javascript
运行
复制
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'})
票数 114
EN

Stack Overflow用户

发布于 2011-08-10 00:47:50

更新: OP使用Python3。所以添加一个使用httplib2的示例

代码语言:javascript
运行
复制
import httplib2

h = httplib2.Http(".cache")

h.add_credentials('name', 'password') # Basic authentication

resp, content = h.request("https://host/path/to/resource", "POST", body="foobar")

以下代码适用于python 2.6:

我在生产中经常使用pycurl来处理一个每天处理1000多万个请求的进程。

您需要首先导入以下内容。

代码语言:javascript
运行
复制
import pycurl
import cStringIO
import base64

基本身份验证头的一部分由编码为Base64的用户名和密码组成。

代码语言:javascript
运行
复制
headers = { 'Authorization' : 'Basic %s' % base64.b64encode("username:password") }

在HTTP头中,您将看到这一行Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=。编码后的字符串会根据用户名和密码的不同而变化。

现在,我们需要一个地方来编写HTTP响应和一个curl连接句柄。

代码语言:javascript
运行
复制
response = cStringIO.StringIO()
conn = pycurl.Curl()

我们可以设置各种卷曲选项。有关完整的选项列表,请访问see this。链接的文档适用于libcurl API,但其他语言绑定的选项不会更改。

代码语言:javascript
运行
复制
conn.setopt(pycurl.VERBOSE, 1)
conn.setopt(pycurlHTTPHEADER, ["%s: %s" % t for t in headers.items()])

conn.setopt(pycurl.URL, "https://host/path/to/resource")
conn.setopt(pycurl.POST, 1)

如果您不需要验证证书。警告:这是不安全的。类似于运行curl -kcurl --insecure

代码语言:javascript
运行
复制
conn.setopt(pycurl.SSL_VERIFYPEER, False)
conn.setopt(pycurl.SSL_VERIFYHOST, False)

调用cStringIO.write来存储HTTP响应。

代码语言:javascript
运行
复制
conn.setopt(pycurl.WRITEFUNCTION, response.write)

当您发出POST请求时。

代码语言:javascript
运行
复制
post_body = "foobar"
conn.setopt(pycurl.POSTFIELDS, post_body)

现在就发出实际的请求。

代码语言:javascript
运行
复制
conn.perform()

根据HTTP响应代码执行一些操作。

代码语言:javascript
运行
复制
http_code = conn.getinfo(pycurl.HTTP_CODE)
if http_code is 200:
   print response.getvalue()
票数 23
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6999565

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档