Unix/Linux系统下基本上都预安装了Python,但有时候它的版本可能不是符合我们要求的。比如在安装osqa–一个基于python和Django框架搭建的问答社区网站开源程序时,对Python的版本要求2.6+,而Centos 5下默认安装的是2.4版本。

因此下面记录的是在Centos Linux vps上编译安装Python 2.7.2,python模块,Apache服务器上启用mod_wsgi,配置Django,搭建osqa开源问答社区网站的步骤。建议编译安装之前先通读全文,这里是按一般编译安装步骤是出现问题,然后解决问题的思路记录的。 

Centos编译安装Python 2.7

下载Python 2 的当前最新版本:

wget http://python.org/ftp/python/2.7.2/Python-2.7.2.tgz
tar -zxpvf Python-2.7.2.tgz -C /opt
cd /opt/Python-2.7.2
./configure

编译安装第一步就出现如下错误,无法继续安装:

checking for –without-gcc… no
checking for gcc… no
checking for cc… no
checking for cl.exe… no
configure: error: in `/opt/Python-2.7.2′:
configure: error: no acceptable C compiler found in $PATH
See `config.log’ for more details

yum -y install gcc

./configure
make
make install

/usr/lib/python2.4/usr/local/lib/python2.7/

Python 模块安装

Python 编译安装完毕后,可能发现一些python模块需要安装。这列举了两种方法:

1.使用Python推荐并自带的Distutils安装模块:下载源码-》解压-》cd到模块解压目录-》执行/usr/local/bin/python2.7 setup.py install –prefix=/usr/local。关于使用Distutils安装Python 模块的官方详细介绍:Installing Python Modules;

2.使用easy_install: 使用easy_install之前要先安装python 的setuptools工具模块:

Setuptools 模块
在下载页面选择2.7版本下载:setuptools-0.6c11-py2.7.egg

cd ~
wget http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg#md5=fe1f997bc722265116870bc7919059ea
sh setuptools-0.6c11-py2.7.egg –prefix=/usr/local

提示错误:

zipimport.ZipImportError: can’t decompress data; zlib not available

(注:也可用ez_setup.py直接安装,或通过yum仓库安装setuptools模块(yum install python-setuptools),不过容易安装在系统默认的python版本中,不是我们需要的编译安装的Python新版本。)

Zlib 模块
上面的错误提示缺少zlib 库,实际上我们在上面编译安装Python结束时就应该出现了这个提示:

Python build finished, but the necessary bits to build these modules were not found:
_bsddb _curses _curses_panel _sqlite3 _ssl _tkinter bsddb185 bz2 dbm gdbm readline sunaudiodev zlib

需要启用zlib模块需要然后重新编译一下Python源码安装包:

cd /opt/Python-2.7.2
vi Modules/Setup
搜索zlib,去掉 #zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz 前面的注释。
./configure
make

又出现错误提示:

./Modules/zlibmodule.c:112: error: ‘compobject’ has no member named
make: *** [Modules/zlibmodule.o] Error 1

Update:上面安装zlib的方法失败,原来Python 2.7得先安装zlib库:

cd /opt/Python-2.7.2/Modules/zlib
./configure make && make install

然后再重新编译安装python,也不用再编辑去掉Modules/Setup文件中的#zlib zlibmodule.c 的注释。
测试一下,无错误提示:

python2.7 >>> import zlib >>> exit()

再回到上面安装setuptools模块的安装,提示成功:

Installing easy_install script to /usr/local/bin
Installing easy_install-2.7 script to /usr/local/bin
Installed /usr/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg

使用easy_install安装其他python模块

easy_install ElementTree Markdown html5lib python-openid

Django 安装

easy_install django django-debug-toolbar

cd ~
wget http://www.djangoproject.com/download/1.3.1/tarball/
tar xzvf Django-1.3.1.tar.gz
cd Django-1.3.1
sudo python2.7 setup.py install

/usr/local/lib/python2.6/dist-packages/Django-1.3.1-py2.6.egg/django

Apache mod_wsgi 安装配置

安装 Apache和mysql : yum install httpd mysql-server
Apache和mysql数据库的安装配置可参考搭建Centos 5.5搭建LAMP
题外话:因nginx启动占用了80端口:

(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down

vi /etc/httpd/conf/httpd.confListen 80

mod_wsgi 安装
下载 mod_wsgi:

wget http://modwsgi.googlecode.com/files/mod_wsgi-3.3.tar.gz
tar xvfz mod_wsgi-3.3.tar.gz -C /opt
cd /opt/mod_wsgi-3.3
./configure –with-python=/usr/local/bin/python

./configure: line 1704: apxs: command not foundyum install httpd-devel

Error: Missing Dependency: httpd = 2.2.3-53.el5.centos.1 is needed by package httpd-devel-2.2.3-53.el5.centos.1.i386 (updates).
Error: Missing Dependency: apr-util = 1.2.7-11.el5_5.2 is needed by package apr-util-devel-1.2.7-11.el5_5.2.i386 (base)

httpd 已经安装,却提示缺少依赖未安装,原因是Apache版本不符。卸载后重新安装相符版本:

yum remove apr-util httpd httpd-tools 我的情况是会同时卸载了依赖 php 5.3.6-1.w5(php-fastcgi不受影响)。
yum install httpd httpd-devel

warning:unused variable / defined but not used

Libraries have been installed in:
/usr/lib/httpd/modules
If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR’
flag during linking and do at least one of the following:
- add LIBDIR to the `LD_LIBRARY_PATH’ environment variable
during execution
- add LIBDIR to the `LD_RUN_PATH’ environment variable
during linking
- use the `-Wl,–rpath -Wl,LIBDIR’ linker flag
- have your system administrator add LIBDIR to `/etc/ld.so.conf’

See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.

make clean:清除编译安装过程中产生的临时文件。

修改Apache 配置文件,启用mod_wsgi模块

vi /etc/httpd/conf/httpd.conf
加入 LoadModule wsgi_module modules/mod_wsgi.so
/etc/init.d/httpd restart

OSQA 搭建配置

yum install MySQL-python

CREATE DATABASE osqa DEFAULT CHARACTER SET UTF8 COLLATE utf8_general_ci;

OSQA 安装

yum install subversion
svn co http://svn.osqa.net/svnroot/osqa/trunk/ /srv/www/osqa
(Checked out revision 1174.)
cd /srv/www/osqa
mkdir cache
chown -R apache:apache .
chmod u+w cache
chmod u+w log
chmod u+w forum/upfiles

编辑osqa.wsgi
cp osqa.wsgi.dist osqa.wsgi
vi osqa.wsgi 加删除线的地方是要修改的
sys.path.append(‘/srv/www‘)
sys.path.append(‘/srv/www/osqa‘)
os.environ['DJANGO_SETTINGS_MODULE'] = ‘osqa.settings’

编辑settings_local.py
cp settings_local.py.dist settings_local.py
vi settings_local.py 修改数据库信息和APP_URL等几个地方:
DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.mysql’,
‘NAME’: ‘osqa数据库名词’,
‘USER’: ‘root用户名’,
‘PASSWORD’: ‘passw密码’,
‘HOST’: ”,
‘PORT’: ”,
}
}
APP_URL = ‘http://farlee.info
LANGUAGE_CODE = ‘zh_CN’ 安装osqa中文版

修改apache配置文件:
vi /etc/httpd/conf.d/mod_wsgi.conf 加入

WSGISocketPrefix /var/run/wsgi
WSGIPythonHome /usr/local/lib/python2.7

#NOTE: all urs below will need to be adjusted if
#settings.FORUM_SCRIPT_ALIAS !=” (e.g. = ‘forum/’)
#this allows “rooting” forum at [http://example.com/forum], if you like
Listen 8080

ServerAdmin admin@your.server.com
DocumentRoot /srv/www/osqa
ServerName farlee.info

#run mod_wsgi process for django in daemon mode
#this allows avoiding confused timezone settings when
#another application runs in the same virtual host
WSGIDaemonProcess OSQA
WSGIProcessGroup OSQA

#force all content to be served as static files
#otherwise django will be crunching images through itself wasting time
Alias /m/ /srv/www/osqa/forum/skins/
Alias /upfiles/ /srv/www/osqa/forum/upfiles/

Order allow,deny
Allow from all

#this is your wsgi script described in the prev section
#this is your wsgi script described in the prev section
WSGIScriptAlias / /srv/www/osqa/osqa.wsgi

CustomLog /var/log/httpd/osqa/access_log common
ErrorLog /var/log/httpd/osqa/error_log

创建相关目录: mkdir -p /var/run/wsgi mkdir /var/log/httpd/osqa

python2.7 manage.py syncdb

File “/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py”, line 14, in
raise ImproperlyConfigured(“Error loading MySQLdb module: %s” % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

yum install python-devel mysql-devel

使用easy_install-2.7 MySQL-python 出现错误:

_mysql.c: In function ‘_mysql_ConnectionObject_getattr’:
_mysql.c:2444: 错误:‘_mysql_ConnectionObject’ 没有名为 ‘open’ 的成员
error: Setup script exited with error: command ‘gcc’ failed with exit status 1

再使用Distutils安装:
下载mysql-python:http://sourceforge.net/projects/mysql-python/
wget http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz/download
tar zxvf MySQL-python-1.2.3.tar.gz -C /opt
cd /opt/MySQL-python-1.2.3
python2.7 setup.py install
出现同样错误:

_mysql.c:36:23: 错误:my_config.h:没有那个文件或目录
_mysql.c:38:19: 错误:mysql.h:没有那个文件或目录
_mysql.c:39:26: 错误:mysqld_error.h:没有那个文件或目录
_mysql.c:40:20: 错误:errmsg.h:没有那个文件或目录
_mysql.c:76: 错误:expected specifier-qualifier-list before ‘MYSQL’
_mysql.c:90: 错误:expected specifier-qualifier-list before ‘MYSQL_RES’
_mysql.c: In function ‘_mysql_Exception’:
_mysql.c:120: 警告:隐式声明函数 ‘mysql_errno’
….
_mysql.c:2422: 错误:初始值设定元素不是常量
_mysql.c:2422: 错误:(在 ‘_mysql_ResultObject_memberlist[0].offset’ 的初始化附近)
_mysql.c: In function ‘_mysql_ConnectionObject_getattr’:
_mysql.c:2444: 错误:‘_mysql_ConnectionObject’ 没有名为 ‘open’ 的成员
error: command ‘gcc’ failed with exit status 1

vi site.cfg#mysql_config = /usr/local/bin/mysql_configmysql_config = /usr/bin/mysql_config

* Red Hat Linux packages:
- mysql-devel to compile
- mysql and/or mysql-devel to run

yum install mysql-develpython2.7 setup.py install

然后再同步数据库:cd -> syncdb
Would you like to create one now? (yes/no): 选择no (osqa搭建好后注册的第一个用户为超级用户)。

无法打开网站,
osqa网站没有错误日志 /var/log/httpd/osqa/error_log;
查看Apache错误日志 vi /var/log/httpd/error_log: ImportError: No module named site

django-admin.py startproject hello

#!.
from django.core import management

if __name__ == “__main__”:
management.execute_from_command_line()

#!/usr/bin/env python

修改Apache配置文件Listen 端口号之后,访问网站出现:503 Service Temporarily Unavailable
The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.

查看apache错误日志:vi /var/log/httpd/error_log

[Fri Sep 23 13:28:38 2011] [error] [client 183.62.15.26] (13)Permission denied: mod_wsgi (pid=32539): Unable to connect to WSGI daemon process ‘hello.djangoserver’ on ‘/etc/httpd/logs/wsgi.32500.0.1.sock’ after multiple attempts.

WSGISocketPrefix /var/run/wsgi

It worked!
Congratulations on your first Django-powered page.
Of course, you haven’t actually done any work yet. Here’s what to do next:
If you plan to use a database, edit the DATABASES setting in hello/settings.py.
Start your first app by running python hello/manage.py startapp [appname].
You’re seeing this message because you have DEBUG = True in your Django settings file and you haven’t configured any URLs. Get to work!

确保mod_wsgi和django都测试成功之后,重启httpd访问osqa站,还是出现出现错误,等待片刻才行:

[Sat Sep 24 08:27:27 2011] [error] [client 183.62.15.26] mod_wsgi (pid=14167): Exception occurred processing WSGI script ‘/srv/www/wsgi/app.wsgi’.
[Sat Sep 24 08:27:27 2011] [error] [client 183.62.15.26] IOError: failed to write data

注意官方教程中设置 WSGIPythonHome 为这种:WSGIPythonHome /usr/local/lib/python2.7
这导致了上面提到的这个错误的出现:ImportError: No module named site
应该用 sys.prefix作为WSGIPythonHome的值,即:WSGIPythonHome /usr/local

继续调试,提示:内部服务器错误500 Internal Server Error

[Sat Sep 24 02:18:19 2011] [error] [client 183.62.15.26]
ExtractionError: Can’t extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg cache:
Permission denied: ‘/var/www/.python-eggs’
The Python egg cache directory is currently set to:
/var/www/.python-eggs
Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory.

mkdir -p /var/python/eggs
/etc/httpd/conf/httpd.conf 文件加入 WSGIPythonEggs /var/python/eggs
设置了仍然无效,WSGIPythonEggs好像只对embedded mode 起作用?
同理httpd.conf设置 SetEnv PYTHON_EGG_CACHE /var/python/eggs 设置仍然无效;
mkdir -p /var/www/.python-eggs
chown -R apache:apache /var/www/.python-eggs
也无效.

只剩load_middleware的错误,去掉httpd.conf中的PYTHON_EGG_CACHE设置,重启apache,终于OSQA界面出现!

—————————-最新版本配置文件—————————

WSGISocketPrefix /var/run/wsgi
WSGIPythonHome /usr/local/
WSGIPythonEggs /var/python/eggs

#NOTE: all urs below will need to be adjusted if
#settings.FORUM_SCRIPT_ALIAS !=” (e.g. = ‘forum/’)
#this allows “rooting” forum at [http://example.com/forum], if you like
Listen 8800

ServerAdmin admin@your.server.com
DocumentRoot /srv/www/osqa
ServerName farlee.info

#run mod_wsgi process for django in daemon mode
#this allows avoiding confused timezone settings when
#another application runs in the same virtual host
WSGIDaemonProcess osqa processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup osqa

#force all content to be served as static files
#otherwise django will be crunching images through itself wasting time
Alias /m/ /srv/www/osqa/forum/skins/

Order allow,deny
Allow from all

Alias /upfiles/ /srv/www/osqa/forum/upfiles/

Order allow,deny
Allow from all

#this is your wsgi script described in the prev section
WSGIScriptAlias / /srv/www/osqa/osqa.wsgi

CustomLog /var/log/httpd/osqa/access_log common
ErrorLog /var/log/httpd/osqa/error_log

关于osqa 1174版本一些问题,参考

1.无法搜索到标题中内容,无法搜索到问题的任何内容(tag 和user可以)
问题描述: http://meta.osqa.net/questions/10378/why-does-question-search-on-my-osqa-instance-not-work
搜索不到内容及解决办法1:http://meta.osqa.net/questions/8198/why-search-engine-is-not-displaying-nothing-no-matter-what-keyword-i-enter
解决办法2:http://meta.osqa.net/questions/8340/facebook-login-wont-login 去掉该模块功能。
解决办法3:使用sphinx 全文搜索http://meta.osqa.net/questions/9215/sphinx-search-isnt-work

http://meta.osqa.net/questions/3404/is-sphinx-search-actively-being-supported

http://meta.osqa.net/questions/6949/can-i-get-search-looking-in-answers-as-well-as-questions-with-mysql-db 搜索问题和答案。

| models.Q(children__body__icontains=keywords)

3. 启用Bootstrap mode更容易获得勋章

4. email 发送仍有问题。apache无错误日志,查看安装目录下的错误日志 vi /srv/www/osqa/log/django.osqa.log

/srv/www/osqa/forum/utils/mail.py TIME: 2011-09-26 05:13:32,636 MSG: mail.py:create_and_send_mail_messages:106 Email sending has failed: No SSL support included in this Python,

安装openssl 后重新编译Python

wget http://www.openssl.org/source/openssl-1.0.0e.tar.gz
tar zxf openssl-1.0.0e.tar.gz -C /opt
cd /opt/openssl-1.0.0e
./config
make
make install

修改Setup.dist

# Socket module helper for socket(2)
#_socket socketmodule.c

# 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

# Andrew Kuchling’s zlib module.
# This require zlib 1.1.3 (or later).
# See http://www.gzip.org/zlib/
zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz

重新编译安装python。完成后发送email测试,出现错误:

class HTTPSConnectionWithTimeout(httplib.HTTPSConnection):
AttributeError: ‘module’ object has no attribute ‘HTTPSConnection’

据说还要安装openssl-devel,已经安装的openssl-devel是0.9.8版本。因此openssl也重新编译安装和openssl-devel 0.9.8e相应的版本:openssl-0.9.8r.tar.gz。

$ ./config
$ make
$ make test
$ make install
再重新编译python
./configure
make

提示现在Python版本其实并不需要修改Modules/Setup来启用某些模块了:

Previous versions of Python used a manual configuration process that
involved editing the file Modules/Setup. While this file still exists
and manual configuration is still supported, it is rarely needed any
more: almost all modules are automatically built as appropriate under
guidance of the setup.py script, which is run by Make after the
interpreter has been built.

If you rerun the configure script with different options, remove all
object files by running “make clean” before rebuilding. Believe it or
not, “make clean” sometimes helps to clean up other inexplicable
problems as well. Try it before sending in a bug report!

5. 修改后pyc文件不更新(python需要重新编译时才自动检查源代码改动),手动编译sudo python -m py_compile ‘/var/www/osqa/settings_local.py’。或者修改之后需要重启apache(清除cache缓存):sudo /etc/init.d/apache2 restart

6. mail settings 使用googke apps
The e-mail settings of this community are not configured yet. We strongly recommend you to do that from the e-mail settings page as soon as possible.
Google app email:http://mail.google.com/support/bin/answer.py?answer=13287

7. 修改其他设置

在Ubuntu 下安装osqa就方便多了,因为python 版本在ubuntu 10.04 之后一般都是python 2.6+。按官方教程配置即可:Ubuntu with Apache and MySQL。