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

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

>>> 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'linux

之因此python内置的urllib模块不支持https协议是由于编译安装python以前没有编译安装相似于openssl这样的SSL库,以致于python不支持SSL算法

由于我用的是CentOS系统因此安装openssl-devel
sudo yum install openssl-develdjango

以后从新编译Python
./configure(可选,由于以前已经配置过,按以前的配置来就好了,并且最好按以前的配置配编译安装以避免依赖的库须要从新编译安装。)
make
make install编程

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

没有再报一样的错误。socket

在安装完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中。url

另外须要特别注意的是,从新编译安装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请求 http://www.linuxidc.com/Linux/2014-10/107903.htm

《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htm

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

本文永久更新连接地址http://www.linuxidc.com/Linux/2014-12/110452.htm

相关文章
相关标签/搜索