Python [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed 解决方法

一个搭建在SAE上的Django应用,使用新浪微博提供的Python SDK已经稳定运行一年有余,但最近开始持续出现微博认证失败的状况。

摘录微博python SDK的错误提示如下所示:

ERROR:django.request:Internal Server Error: /weibo/auth/
Traceback (most recent call last):
  File "/usr/local/sae/python/3rd/django-1.5/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/data1/www/htdocs/838/app/1/mysite/views.py", line 42, in auth
    res = weibo_util.keep_user(code,api,redirect_uri)
  File "/data1/www/htdocs/838/app/1/util/weibo_util.py", line 86, in keep_user
    r = client.request_access_token(code,redirect_url)
  File "/data1/www/htdocs/838/app/1/weibo.py", line 255, in request_access_token
    code = code, grant_type = 'authorization_code')
  File "/data1/www/htdocs/838/app/1/weibo.py", line 114, in _http_post
    return _http_call(url, _HTTP_POST, authorization, **kw)
  File "/data1/www/htdocs/838/app/1/weibo.py", line 155, in _http_call
    resp = urllib2.urlopen(req)
  File "/usr/local/sae/python/lib/python2.7/urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/local/sae/python/lib/python2.7/urllib2.py", line 431, in open
    response = self._open(req, data)
  File "/usr/local/sae/python/lib/python2.7/urllib2.py", line 449, in _open
    '_open', req)
  File "/usr/local/sae/python/lib/python2.7/urllib2.py", line 409, in _call_chain
    result = func(*args)
  File "/usr/local/sae/python/lib/python2.7/urllib2.py", line 1240, in https_open
    context=self._context)
  File "/usr/local/sae/python/lib/python2.7/urllib2.py", line 1197, in do_open
    raise URLError(err)
URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:606)> yq66 

问题的原因是“SSL: CERTIFICATE_VERIFY_FAILED”。

Google到了这样一篇博文,对解决问题提供了很大的帮助,原文链接:http://reality0ne.com/2014/12/816/

Python 升级到 2.7.9 之后引入了一个新特性,当使用urllib.urlopen打开一个 https 链接时,会验证一次 SSL 证书。
而当目标网站使用的是自签名的证书时就会抛出一个 urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)> 的错误消息,详细信息可以在这里查看(https://www.python.org/dev/peps/pep-0476/)。

解决方案包括下列两种方式:

1. 使用ssl创建未经验证的上下文,在urlopen中传入上下文参数

import ssl
import urllib2

context = ssl._create_unverified_context()
print urllib2.urlopen("https://www.12306.cn/mormhweb/", context=context).read()

2. 全局取消证书验证

import ssl
import urllib2
 
ssl._create_default_https_context = ssl._create_unverified_context
 
print urllib2.urlopen("https://www.12306.cn/mormhweb/").read()

 在此使用方法2,修改weibo.py,在第155行添加下列代码:

import ssl
ssl._create_default_https_context = ssl._create_unverified_context

至此,问题圆满解决!

本文链接:http://bookshadow.com/weblog/2015/04/22/sae-python-weibo-sdk-certificate-verify-failed/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

 

posted @ 2017-09-05 18:22  bcombetter  阅读(788)  评论(0编辑  收藏  举报