python开发环境搭建

来源:互联网 发布:矩阵秩的性质 编辑:程序博客网 时间:2024/05/20 00:38
我安装的是CentOS 7
CentOS 7上面的Python版本已经是2.7.5,所以不用安装新版本了

第一步:安装需要的开发包

yum groupinstall "Development tools"yum install zlib-devel bzip2-devel pcre-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel python-devel

CentOS 自带Python2.6.6,但我们可以再安装Python2.7.5:

cd ~wget http://python.org/ftp/python/2.7.5/Python-2.7.5.tar.bz2tar xvf Python-2.7.5.tar.bz2cd Python-2.7.5./configure --prefix=/usr/localmake && make altinstall

安装完毕后,可是使用”python2.7”命令进入python2.7的环境。


第二步:安装Python包管理easy_install

easy_install包 https://pypi.python.org/pypi/distribute

方便安装Python的开发包

cd ~wget https://pypi.python.org/packages/source/d/distribute/distribute-0.6.49.tar.gztar xf distribute-0.6.49.tar.gzcd distribute-0.6.49python setup.py installeasy_install --version

注:若安装了新版本Python,则红色部分必须是当前对应的Python版本,否则会安装到系统默认的Python中。

pip包 https://pypi.python.org/pypi/pip

安装pip的好处是可以pip list、pip uninstall 管理Python包, easy_install没有这个功能,只有uninstall

easy_install pippip --version

第三步:安装uwsgi

uwsgi:https://pypi.python.org/pypi/uWSGI

uwsgi参数详解:http://uwsgi-docs.readthedocs.org/en/latest/Options.html

pip install uwsgiuwsgi --version

在安装uWSGI的时候有可能提示说是libxml2不存在,针对此情况,建议通过 yum install libxml2-devel来解决</font>

raise Exception("you need a C compiler to build uWSGI")

    Exception: you need a C compiler to build uWSGI

出现以上错误是因为没有c的编译器,执行:yum install gcc  

  (ubuntu下可用apt-get install libxml2-dev)

    如编译出现下问题:

     In file included from plugins/python/python_plugin.c:1:0:
    plugins/python/uwsgi_python.h:2:20: fatal error: Python.h: No such file or directory
    compilation terminated.

    需安装python-devel(ubuntu下出现依赖问题,可使用aptitude install python-dev)

测试uwsgi是否正常:

新建test.py文件,内容如下:

def application(env, start_response):        start_response('200 OK', [('Content-Type','text/html')])        return "Hello World"

然后在终端运行:

uwsgi --http :8001 --wsgi-file test.py

在浏览器内输入:http://127.0.0.1:8001,看是否有“Hello World”输出。


第四步:安装其他框架

安装MySQL数据库  
#yum -y install mysql mysql-server mysql-devel libdbi-dbd-mysql  
#service mysqld start  
#chkconfig mysqld on 

安装MySQLdb (  mysql-python )  
#easy_install mysql-python 

安装web.py (  官网 )  
#easy_install web.py

或者

安装webpy

$ wget http://webpy.org/static/web.py-0.34.tar.gz

$ tar xvzf web.py-0.34.tar.gz

$ cd web.py-0.34

$ sudo python setup.py install



安装 Spawn-fcgi

wget http://www.lighttpd.net/download/spawn-fcgi-1.6.3.tar.gz

tar zxvf spawn-fcgi-1.6.3.tar.gz

cd spawn-fcgi-1.6.3

./configure --prefix=/usr  设置到/usr

make && make install 




安装 Flup

$ wget http://www.saddi.com/software/flup/dist/flup-1.0.2.tar.gz

$ tar xvzf flup-1.0.2.tar.gz

$ cd flup-1.0.2

$ sudo python setup.py install


第五步:安装nginx


wget http://nginx.org/download/nginx-1.5.6.tar.gz

tar xf nginx-1.5.6.tar.gz

mv nginx-1.5.6 nginx

cd nginx

./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_gzip_static_module

make && make install

ln -s /usr/local/nginx/sbin/nginx /usr/sbin/nginx 


:若中间安装过程中出现错误,如:

Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_root/matplotlib/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-ModyBS-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_root/matplotlib

之类的,有可能没有装好依赖包,比如prepython等等,重新安装一下依赖包

yum install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel python-devle等


一切安装完成之后开始配置
配置uwsgi:

uwsgi 的配置文件 可支持xml yaml ini等格式。这里使用ini格式的配置文件。默认路径为/etc/uwsgi.ini。 

[uwsgi] #使用动态端口,启动后将端口号写入以下文件中socket = /tmp/uwsgi_vhosts.sock#也可以指定使用固定的端口#socket=127.0.0.1:9031 pidfile=/var/run/uwsgi.pid daemonize=/var/log/uwsgi.log master=true vhost=true gid=nginx uid=nginx #性能相关的一些参数,具体内容查看官网文档workers=50max-requests=5000 limit-as=512

8. 创建uwsgi开机自启动脚本,便于进行系统管理  
vi /etc/init.d/uwsgi,内容如下: 

#! /bin/sh  # chkconfig: 2345 55 25  # Description: Startup script for uwsgi webserver on Debian. Place in /etc/init.d and  # run 'update-rc.d -f uwsgi defaults', or use the appropriate command on your  # distro. For CentOS/Redhat run: 'chkconfig --add uwsgi'  ### BEGIN INIT INFO  # Provides: uwsgi  # Required-Start: $all  # Required-Stop:  $all  # Default-Start:  2 3 4 5  # Default-Stop:0 1 6  # Short-Description: starts the uwsgi web server  # Description: starts uwsgi using start-stop-daemon  ### END INIT INFO  PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin  DESC="uwsgi daemon"  NAME=uwsgi  DAEMON=/usr/bin/uwsgi  CONFIGFILE=/etc/$NAME.ini  PIDFILE=/var/run/$NAME.pid  SCRIPTNAME=/etc/init.d/$NAME  set -e  [ -x "$DAEMON" ] || exit 0  do_start() {     $DAEMON $CONFIGFILE || echo -n "uwsgi already running"  }  do_stop() {     $DAEMON --stop $PIDFILE || echo -n "uwsgi not running"     rm -f $PIDFILE     echo "$DAEMON STOPED."  }  do_reload() {     $DAEMON --reload $PIDFILE || echo -n "uwsgi can't reload"  }  do_status() {     ps aux|grep $DAEMON  }  case "$1" in   status)     echo -en "Status $NAME: \n"     do_status   ;;   start)     echo -en "Starting $NAME: \n"     do_start   ;;   stop)     echo -en "Stopping $NAME: \n"     do_stop   ;;   reload|graceful)     echo -en "Reloading $NAME: \n"     do_reload   ;;   *)     echo "Usage: $SCRIPTNAME {start|stop|reload}" >&2     exit 3   ;;  esac  exit 0

将脚本属性修改为可执行:  
#chmod 755 /etc/init.d/uwsgi 

启用开机自动启动:  
#chkconfig uwsgi on 

启动uwsgi服务:  
#service uwsgi start

配置nginx:

配置nginx下的uwsgi站点  
例如新增以下一个站点mysite。  
vi /etc/nginx/conf.d/mysite.conf, 内容: 

server {   listen  9091;   server_name  localhost;   root /www/mysite;   index index.html index.htm;   access_log /var/log/nginx/mysite_access.log;   error_log /var/log/nginx/mysite_error.log;   location / {     #使用动态端口    uwsgi_pass unix:///tmp/uwsgi_vhosts.sock;    #uwsgi_pass 127.0.0.1:9031;     include uwsgi_params;     uwsgi_param UWSGI_SCRIPT uwsgi;       uwsgi_param UWSGI_PYHOME $document_root;     uwsgi_param UWSGI_CHDIR  $document_root;   } }

设置nginx开机启动,在/ect/init.d/目录下新建nginx文件,内容如下:

#!/bin/sh

#

# nginx - this script starts and stops the nginx daemon

#

# chkconfig:   - 85 15

# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \

#               proxy and IMAP/POP3 proxy server

# processname: nginx

# config:      /usr/local/nginx/conf/nginx.conf

# pidfile:     /var/run/nginx.pid

  

# Source function library.

. /etc/rc.d/init.d/functions

  

# Source networking configuration.

. /etc/sysconfig/network

  

# Check that networking is up.

[ "$NETWORKING" = "no" ] && exit 0

  

nginx="/usr/local/nginx/sbin/nginx"

prog=$(basename $nginx)


NGINX_CONF_FILE="/etc/nginx/conf/mysite.conf"

  

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

  

lockfile=/var/lock/subsys/nginx  

 

start() {

    [ -x $nginx ] || exit 5

    [ -f $NGINX_CONF_FILE ] || exit 6

    echo -n $"Starting $prog: "

    daemon $nginx -c $NGINX_CONF_FILE

    retval=$?

    echo

    [ $retval -eq 0 ] && touch $lockfile

    return $retval

}

  

stop() {

    echo -n $"Stopping $prog: "

    killproc $prog -QUIT

    retval=$?

    echo

    [ $retval -eq 0 ] && rm -f $lockfile

    return $retval

}

  

restart() {

    configtest || return $?

    stop

    sleep 1

    start

}

  

reload() {

    configtest || return $?

    echo -n $"Reloading $prog: "

    killproc $nginx -HUP

    RETVAL=$?

    echo

}

  

force_reload() {

    restart

}

  

configtest() {

  $nginx -t -c $NGINX_CONF_FILE

}

  

rh_status() {

    status $prog

}

  

rh_status_q() {

    rh_status >/dev/null 2>&1

}

  

case "$1" in

    start)

        rh_status_q && exit 0

        $1

        ;;

    stop)

        rh_status_q || exit 0

        $1

        ;;

    restart|configtest)

        $1

        ;;

    reload)

        rh_status_q || exit 7

        $1

        ;;

    force-reload)

        force_reload

        ;;

    status)

        rh_status

        ;;

    condrestart|try-restart)

        rh_status_q || exit 0

            ;;

    *)

        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"

        exit 2

esac


nginx


10. 启动Nginx服务  
#service nginx start  

如果权限不够

chmod 755 nginx

#chkconfig nginx on 

三、编写一个Hello World!  
#vi /www/mysite/hello.py,内容: 

#!/usr/bin/env python# -*- coding: utf-8 -*-  import weburls = (  '/t', 'test', #测试  '/', 'home')app = web.application(urls, globals())#返回wsgi接口application = app.wsgifunc()class test:  '测试'    def GET(self):    # 开发测试用    referer = web.ctx.env.get('HTTP_REFERER', 'http://google.com')    client_ip = web.ctx.env.get('REMOTE_ADDR')    host = web.ctx.env.get('host')    fullpath = web.ctx.fullpath    user_agent = web.ctx.env.get('HTTP_USER_AGENT')    data = ""    data += 'Client: %s<br/>\n' % client_ip    data += 'User-agent: %s<br/>\n' % user_agent    data += 'FullPath: %s<br/>\n' % fullpath    data += 'Referer: %s<br/>\n' % referer    return data  def POST(self):    passclass home:  '根目录请求的处理'  def GET(self):    return "Hello Web.py"  def POST(self):    return self.GET()if __name__ == "__main__":  app.run()

浏览器访问:

http://localhost:9091/

http://localhost:9091/t


我是这么配置的:

listen  9091; 

server_name  localhost; 

   index index.html index.htm; 

   access_log /var/log/nginx/mysite_access.log; 

   error_log /var/log/nginx/mysite_error.log; 

   location / {


include fastcgi_params;

     fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;  # [1]

     fastcgi_param PATH_INFO $fastcgi_script_name;        # [2]

     fastcgi_pass 127.0.0.1:9016;


        } 


然后在home文件夹下创建www目录里面写三个文件:debug.sh restart.sh webmain.py

debug.sh:

#!/bin/sh


#kill qunxianhui_dev server

clear

echo '-----get current path ----------'

filepath=$(cd "$(dirname "$0")"; pwd)

echo $filepath

webmainpy="$filepath""/webmain.py"


echo '-----search all process ID------'

pidlists=`ps -ef | grep $webmainpy | grep -v 'grep' |awk '{print $2}'`


echo "$pidlists"


if [ -n "$pidlist"  ]

then

echo "no pid"

echo "--------------finish----------------"


else

kill -9 $pidlists

echo "KILL $pidlists"

fi



echo "wait 1 seconds........."

sleep 1

echo "start 9016 port debug....."

/usr/bin/spawn-fcgi -d $filepath -f $webmainpy -p 9016 -a 127.0.0.1 -n


restart.sh:

#!/bin/sh


#kill qunxianhui_dev server

clear

echo '-----get current path ----------'

filepath=$(cd "$(dirname "$0")"; pwd)

echo $filepath

webmainpy="$filepath""/webmain.py"


echo '-----search all process ID------'

pidlists=`ps -ef | grep $webmainpy | grep -v 'grep' |awk '{print $2}'`


echo "$pidlists"


if [ -n "$pidlist"  ]

then

echo "no pid"

echo "--------------finish----------------"


else

kill -9 $pidlists

echo "KILL $pidlists"

fi



echo "wait 1 seconds........."

sleep 1

echo "start 9016 port....."

/usr/bin/spawn-fcgi -d $filepath -f $webmainpy -p 9016 -a 127.0.0.1 -F 7


webmain.py:

#!/usr/bin/env python

#coding=UTF-8


import web

import sys

import json

import os

from logging import * 

from datetime import *

import time

import datetime

reload(sys)

import uuid

sys.setdefaultencoding('utf-8')


from web.net import htmlquote as quote

import httplib


import hashlib



urls = (

    '/test','test',

    '/h','hello'

)



app = web.application(urls, globals())



class test:

def GET(self):

return 'hello world'


class hello:

    def GET(self):

        return "hello baolongsdf"



if __name__ == "__main__":

    web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr)

    app.run()


然后sh debug.sh 在浏览器中输入http://127.0.0.1:9091/test 这样就可以hello world了

CentOS 7中默认使用Firewalld做防火墙,所以修改iptables后,在重启系统后,根本不管用。 

Firewalld中添加端口方法如下: 

firewall-cmd --zone=public --add-port=3306/tcp —permanent 

firewall-cmd --zone=public --add-port=22/tcp --permanent 

firewall-cmd --zone=public --add-port=9091/tcp --permanent 

firewall-cmd --reload



番外篇:

这篇文章主要是关于Nginx在编译安装时,可能出现的错误的解决方法。Nginx正确的编译安装操作见前文 《2015博客升级记(三):CentOS 7.1编译安装Nginx1.9.0》 。 

1 Nginx启动脚本错误:env: /etc/init.d/nginx: No such file or directory

明明上传了Nginx服务控制脚本 nginx ,但是在执行 service nginx start命令时,却会报上面的错误。 

解决方法:启动脚本的格式有问题,例如该脚本是dos格式,在Linux系统是中无法识别的。可以通过vim打开该文件,如果可以看到出现 ^M 的字符,就可以确定是DOS格式的了。那么可以在vim中执行命令 :%s/\r\+$//e ,将其转换成Unix格式即可。 

2 启动Nginx服务失败

安装完Nginx后,执行命令 service nginx start 失败,即无法正常启动Nginx服务。 

[root@typecodes init.d]# service nginx startStarting nginx (via systemctl):  Warning: Unit file of nginx.service changed on disk, 'systemctl daemon-reload' recommended.Job for nginx.service failed. See 'systemctl status nginx.service' and 'journalctl -xn' for details.[FAILED]

解决方法:主要通过命令 systemctl status nginx.service 来分析,如下图所示。 

很明显是由于下面这个错误,导致Nginx服务启动失败。

Apr 11 21:43:07 typecodes nginx[4026]: Starting nginx: nginx: [emerg] mkdir() "/var/tmp/nginx/client/" failed (2: No such file or directory)

这种错误一般都是目录不存在或者权限不足,所以直接执行下面两条命令即可。

[root@typecodes ~]# cd /var/tmp/[root@typecodes ~]# mkdir -p /var/tmp/nginx/{client,proxy,fastcgi,uwsgi,scgi}

3 启动Nginx服务时,界面卡住

在敲入命令 service nginx restart 后,终端界面能卡住,也就是Nginx服务控制脚本 nginx 没有正常执行完毕。在停止Nginx服务后,发现Nginx进程还存在。 

#######启动Nginx服务出现警告[root@typecodes init.d]# service nginx restart Restarting nginx (via systemctl):  Warning: Unit file of nginx.service changed on disk, 'systemctl daemon-reload' recommended.Restarting nginx (via systemctl):  Warning: Unit file of nginx.service changed on disk, 'systemctl daemon-reload' recommended.^C     ######终端界面卡住,使用ctrl+c命令强制结束#######停掉Nginx服务[root@typecodes init.d]# service nginx stopStopping nginx (via systemctl):  [  OK  ]#######查看Nginx进程是否已被停止(可以看到未停止)[root@typecodes init.d]# ps -aux|grep nginx root      7796  0.0  0.2  84184  2044 ?        Ss   21:14   0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.confnginx     7798  0.0  0.3  86656  3380 ?        S    21:14   0:00 nginx: worker processroot      7981  0.0  0.0 112644   964 pts/0    S+   21:19   0:00 grep --color=auto nginx

解决方法:可能是Nginx服务控制脚本(/etc/init.d/nginx)代码不正确,推荐使用文章 《Nginx服务启动、停止和重启等操作的SHELL脚本》 中的shell脚本。最后再重新执行下面的脚本即可。 

[root@typecodes init.d]# chkconfig --add nginx[root@typecodes init.d]# chkconfig nginx on[root@typecodes init.d]# service nginx restart

还有一种在启动Nginx服务时,终端界面会卡住的情况:那就是Nginx的配置文件 /etc/nginx/nginx.conf 不正确,但是使用 nginx -t 命令显示正常。这种情况只能对nginx.conf文件中的每一个配置进行检查了。 

4 Compilation failed in require或者perl_parse() failed

在使用命令 service nginx start 启动Nginx服务时报错,于是通过 systemctl status nginx.service 查看具体的错误信息。 

然后使用命令 nginx -t 查看配置是否正常,如下图所示,同样报错。 

解决方法:从图中可以看出由于 Can't load '/usr/local/lib64/perl5/auto/nginx/nginx.so' for module nginx: /usr/local/lib64/perl5/au...m line 68. 的错误,导致了Nginx在调用函数时失败: perl_parse() failed 。也就是证明是之前没有安装perl依赖包,于是通过执行命令 yum -y install perl-devel perl-ExtUtils-Embed 后,再次编译安装Nginx解决。











0 0
原创粉丝点击