python开发环境安装及restapi demo开发

linux下安装

linux中一般默认安装python,在命令行中输入python,查看当前版本

1
2
3
4
$ python
Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2

在安装python之前先安装sqlite-devel,否则随后运行django时可能会报错,错误内容为django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3。运行命令

1
yum install sqlite-devel

当前版本是2.6.6,安装的版本是2.7.11

  • 下载python的二进制包 Python-2.7.11.tgz 并解压
  • 进入解压后的目录中 运行 如下命令
1
2
3
./configure
make
make install (权限有问题,则执行 sudo make install)

(source ~/.bashrc)再次运行python,如果发现版本依然没有发生变化,则继续执行下面的命令

1
2
3
4
sudo su - root
cd /usr/bin
rm -rf python
ln -s ${PYTHON_HOME}/python python

此时python安装成功,但可能会导致centos的yum命令无法使用,提示如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ yum
There was a problem importing one of the Python modules
required to run yum. The error leading to this problem was:
No module named yum
Please install a package which provides this module, or
verify that the module is installed correctly.
It's possible that the above module doesn't match the
current version of Python, which is:
2.7.11 (default, Apr 19 2016, 14:52:39)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)]
If you cannot solve this problem yourself, please go to
the yum faq at:
http://yum.baseurl.org/wiki/Faq

此问题是由于机器上有多个python版本,而yum依赖的版本与默认的python版本不一致造成的,修改yum,将开头的#!/usr/bin/python改为#!/usr/bin/python2.6

1
2
which yum
vim /usr/bin/yum

安装pip,用来安装第三方包

在安装pip之前,要先安装setuptools

  • wget –no-check-certificate https://bootstrap.pypa.io/ez_setup.py
  • python ez_setup.py –user (在用户目录下安装)
  • python ez_setup.py –insecure (需要管理员权限)
    【如果使用 –user,安装pip时,报找不到setuptools模块,则使用–insecure安装】

安装pip

  • 下载pip pip-8.1.1.tar.gz,解压并进入该目录中
  • sudo python setup.py install

安装python的虚拟环境virtualenv

pip install virtualenv (root or sudo)

在virtualenv环境中创建应用

新建个目录,用于存放python项目

1
2
mkdir djangorest
cd djangorest
  1. 创建虚拟环境,命令virtualenv djangoenv
  2. 激活虚拟环境,命令source djangoenv/bin/activate,此时命令行显示如下
1
(djangoenv) [hadoop@centos djangorest]$

rest api demo开发

安装第三方依赖包

1
2
3
4
pip install django
pip install djangorestframework
pip install uwsgi
pip install MySQL-python

安装pyhs2
yum install gcc-c++
yum install python-devel.x86_64 cyrus-sasl-devel.x86_64
pip install pyhs2

创建web application

1
2
django-admin.py startproject restful . #("."代表当前目录)
python manage.py startapp rest

编辑rest/views.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -*- coding: UTF-8 -*-
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.http import HttpResponse
import os
import sys
# REST接口测试
@api_view(['GET', 'POST'])
def restapitest(request):
response = HttpResponse()
if request.method == 'POST':
response.write("This method is post.")
return response
elif request.method == 'GET':
response.write("This method is get.")
return response

创建rest/urls.py

1
2
3
4
5
6
7
8
9
10
11
12
13
# -*- coding: utf-8
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework.routers import DefaultRouter
from . import views
urlpatterns = [
url(r'^restapitest/$', views.restapitest, name = 'restapitest'),
]
urlpatterns = format_suffix_patterns(urlpatterns)

restful/urls.py中添加

1
2
3
4
5
from django.conf.urls import include, url
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^rest/', include('rest.urls')),
]

编译测试脚本rest.test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#coding=utf-8
import sys
import os
import urllib
import urllib2
def get(url, data):
#req = urllib2.Request(url)
data = urllib.urlencode(data)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
#response = opener.open(req + "?" + data)
response = opener.open("%s?%s"%(url, data))
print data
return response.read()
def post(url, data):
req = urllib2.Request(url)
data = urllib.urlencode(data)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
response = opener.open(req, data)
print data
return response.read()
def gettest():
posturl = "http://xxxx:8000/rest/restapitest"
data = dict(fromDate="2016-02-02",toDate="2016-02-24")
print posturl
print get(posturl, data)
def posttest():
posturl = "http://xxxx:8000/rest/restapitest"
data = dict(fromDate="2016-02-02",toDate="2016-02-04")
print posturl
print post(posturl, data)
if __name__ == '__main__':
#gettest()
posttest()

uwsgi启动server (加&,表示后台运行)

1
uwsgi --socket xxxx:8000 --chdir /xxx/djangorest/ --wsgi-file restful/wsgi.py --protocol=http --pidfile rest-uwsgi.pid

运行测试脚本,或者从浏览器访问

1
python rest.test
您的肯定,是我装逼的最大的动力!