Python内置的urllib模块不支持https协议的解决办法


Django站点使用django_cas接入SSO(单点登录系统),配置完成后登录,抛出“urlopen error unknown url type: https”异常。寻根朔源发现是python内置的urllib模块不支持https协议。

>>> import urllib
>>> urllib.urlopen('http://www.baidu.com')
<addinfourl at 269231456 whose fp = <socket._fileobject object at 0xff98250>>
>>> urllib.urlopen('https://www.baidu.com')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/python27/lib/python2.7/urllib.py", line 86, in urlopen
    return opener.open(url)
  File "/usr/local/python27/lib/python2.7/urllib.py", line 204, in open
    return self.open_unknown(fullurl, data)
  File "/usr/local/python27/lib/python2.7/urllib.py", line 216, in open_unknown
    raise IOError, ('url error', 'unknown url type', type)
IOError: [Errno url error] unknown url type: 'https'

之所以python内置的urllib模块不支持https协议是因为编译安装python之前没有编译安装类似于openssl这样的SSL库,以至于python不支持SSL

因为我用的是CentOS系统所以安装openssl-devel
sudo yum install openssl-devel

之后重新编译Python
./configure(可选,因为之前已经配置过,按之前的配置来就行了,而且最好按之前的配置配编译安装以免依赖的库需要重新编译安装。)
make
make install

>>> import urllib
>>> urllib.urlopen('https://www.baidu.com')

没有再报同样的错误。

在安装完openssl-devel后重新编译python前也有说需要编辑Modules文件夹内Setup.dist文件的
修改
# Socket module helper for SSL support; you must comment out the other
# socket line above, and possibly edit the SSL variable:
#SSL=/usr/local/ssl
#_ssl _ssl.c \
#        -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
#        -L$(SSL)/lib -lssl -lcrypto

 # Socket module helper for SSL support; you must comment out the other
# socket line above, and possibly edit the SSL variable:
SSL=/usr/local/ssl
_ssl _ssl.c \
        -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
        -L$(SSL)/lib -lssl -lcrypto

但实际测试下来好像并不需要修改这个文件,编译的时候能自动将SSL库编译进python中。

另外需要特别注意的是,重新编译安装python后,通过可执行文件名(可能是个连接文件)运行python可能运行的还是老的python,这是因为可执行文件名没有连接到新的python可执行程序。因此要用最新的python可执行文件名或指向该名字的连接来运行python。

重新编译安装python后有可能导致需要重新编译django,MySQLdb,pycrypto,python-ldap,django-auth-ldap,django_cas,django_cas,pymongo等一些列依赖python的模块。这里要特别注意

Python向PHP发起GET与POST请求

《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版]

《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码]

Python脚本获取Linux系统信息

在Ubuntu下用Python搭建桌面算法交易研究环境

Python 语言的发展简史

Python 的详细介绍:请点这里
Python 的下载地址:请点这里

本文永久更新链接地址:

相关内容