python用requests请求百度接口报“SSL: CERTIFICATE_VERIFY_FAILED”

来源:互联网 发布:阿里云虚拟主机优惠 编辑:程序博客网 时间:2024/05/01 09:46

SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)

今天想试用一下百度的语音识别API,附带步骤:

1. 先去百度开放云平台注册,成为开发者,审核可能需要时间的,我去年申过现在账号还在

2. 然后创建一个应用

3.为创建完的应用添加服务,有俩,语音识别和语音生成

4. 这样我就有一个调用他语音识别接口的access_token了,这个token由于我采用的是API For Rest,要拿API_keysecret_key通过一个http请求获得,问题就出在这儿了


我用request按照他文档的样子Post了一下,又Get了一下都报一个验证失败的错误。

requests.post('https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=xxxxxxx&client_secret=xxxxxxx').content

requests.get('https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=xxxxxxx&client_secret=xxxxxxx').content

他告诉我:

SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)


找了一下,有人说原因是这样的:

Python 2.7.9 之后引入了一个新特性
当你urllib.urlopen一个 https 的时候会验证一次 SSL 证书 
当目标使用的是自签名的证书时就会爆出一个 
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)> 的错误消息


确实我用urllib试了一下结果一样,requests跟urllib是一样的。


那么要解决这个问题,PEP-0476的文档说

For users who wish to opt out of certificate verification on a single connection, they can achieve this by providing the contextargument to urllib.urlopen :

import ssl# This restores the same behavior as before.context = ssl._create_unverified_context()urllib.urlopen("https://no-valid-cert", context=context)
It is also possible, though highly discouraged , to globally disable verification by monkeypatching the ssl module in versions of Python that implement this PEP:

import ssltry:    _create_unverified_https_context = ssl._create_unverified_contextexcept AttributeError:    # Legacy Python that doesn't verify HTTPS certificates by default    passelse:    # Handle target environment that doesn't support HTTPS verification    ssl._create_default_https_context = _create_unverified_https_context

就是说你可以禁掉这个证书的要求,urllib来说有两种方式,一种是urllib.urlopen()有一个参数context,把他设成ssl._create_unverified_context

或者修改现在的全局默认值

_create_unverified_https_context

ssl._create_default_https_context

ssl._create_unverified_context

测试了一下,确实可以,返回了几个token,那么requests呢,难道必须设置全局变量吗。

其实requestpostget都有一个叫verify的参数,把他设成False就可以了。

print requests.get('https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=xxxxx&client_secret=xxxxxxxx', verify=False).content














0 0
原创粉丝点击