搭建目标如下:

          图:系统架构图

这个系统可以提供web服务及其它查询应用服务,我用其做一个二手房信息搜集、处理及分发的系统,可以通过浏览器访问,也可以通过定制的客户端进行访问。

一、安装篇

1、下载安装python

  1. # wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz
  2. #
  3. # tar xvfz Python-2.7.3.tgz
  4. # cd Python-2.7.3
  5. #./configure
  6. # make
  7. # sudo make install

下面是一些python安装工具,可以方便的安装所缺模块

python的包管理setuptools安装

  1. # wget http://peak.telecommunity.com/dist/ez_setup.py
  2. # python ez_setup.py

python的包管理pip安装(需要先安装setuptools)

  1. # wget http://python-distribute.org/distribute_setup.py
  2. # python distribute_setup.py
  3. # wget https://github.com/pypa/pip/raw/master/contrib/get-pip.py
  4. # python get-pip.py

下面使用pip 安装readline

  1. # sudo pip install readline

2、下载安装Django

  1. # wget https://www.djangoproject.com/download/1.4.3/tarball/
  2. #
  3. # tar xvfz Django-1.4.3.tar.gz
  4. # cd Django-1.4.3
  5. # sudo python setup.py install

3、下载安装MongoDB

l  先下载安装scons

  1. # wget http://sourceforge.net/projects/scons/files/scons/2.1.0.alpha.20101125/scons-2.1.0.alpha.20101125.tar.gz/download
  2. #
  3. # tar xvfz scons-2.1.0.alpha.20101125.tar.gz
  4. # cd scons-2.1.0.alpha.20101125
  5. # sudo python setup.py install

l  下载安装MongoDB

  1. # wget http://downloads.mongodb.org/src/mongodb-src-r2.2.2.tar.gz
  2. #
  3. # tar xvfz mongodb-src-r2.2.2.tar.gz
  4. # cd mongodb-src-r2.2.2
  5. # scons all
  6. # sudo scons --prefix=/usr/local/mongodb --full install

l  下载安装pyMongo

  1. # wget wget http://pypi.python.org/packages/source/p/pymongo/pymongo-2.4.2.tar.gz
  2. #
  3. # tar xvfz pymongo-2.4.2.tar.gz
  4. # cd pymondo-2.4.2
  5. # sudo python setup.py install

测试pyMongo是否安装成功

  1. # python
  2. > import pymongo

如果没有返回错误,则表明安装成功。

l  下载安装mongoengine【暂时没有用到】

  1. # wget http://github.com/mongoengine/mongoengine/tarball/v0.6.20 --no-check-certificate
  2. #
  3. # tar xvfz v0.6.20
  4. # cd MongoEngine-mongoengine-9cc6164
  5. # sudo python setup.py install

测试mongoengine是否安装成功

  1. # python
  2. > from mongoengine import connect

如果没有返回错误,则表明安装成功。

4、下载安装MySQL

l  先下载安装cmake:

  1. # wget http://www.cmake.org/files/v2.8/cmake-2.8.8.tar.gz
  2. #
  3. # tar xvfz cmake-2.8.8.tar.gz
  4. # cd cmake-2.8.8
  5. #./configure
  6. # make
  7. # sudo make install

l  下载安装mysql

  1. # wget http://cdn.mysql.com/Downloads/MySQL-5.5/mysql-5.5.29.tar.gz
  2. #
  3. # tar xvfz mysql-5.5.29.tar.gz
  4. # cd mysql-5.5.29
  5. # cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DMYSQL_DATADIR=/usr/localmysql/data/ -DMYSQL_UNIX_ADDR=/usr/localmysql/data/mysqld.sock -DWITH_INNOBASE_STORAGE_ENGINE=1 -DSYSCONFDIR=/etc -DEXTRA_CHARSETS=all -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_unicode_ci -DWITH_DEBUG=0
  6. # make
  7. # sudo make install

l  下载安装mysql-python

  1. # wget http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz
  2. #
  3. # tar xvfz MySQL-python-1.2.3.tar.gz
  4. # cd MySQL-python-1.2.3

在安装前,需要修改site.py中mysql_config的路径(为mysql安装路径下的/bin/mysql_config),

  1. # site.py
  2. mysql_config = /usr/local/mysql/bin/mysql_config

更改完后,可以进行编译和安装了

  1. # python setup.py build
  2. # sudo python setup.py install

通过测试import MySQLdb来判断是否安装成功,这里还需要将mysql安装路径下的lib加入到环境变量LD_LIBRARY_PATH中。

  1. # export LD_LIBRARY_PATH=/usr/local/mysql/lib/:$LD_LIBRARY_PATH

注:cmake选项说明

选项

说明

-DCMAKE_INSTALL_PREFIX

mysql安装的主目录。默认为/usr/local/mysql

-DMYSQL_DATADIR

mysql数据保存的路径自定义

-DMYSQL_UNIX_ADDR

系统Socket文件(.sock)设置基于该文件路径进行Socket连接必要为绝对路径

-DWITH_INNOBASE_STORAGE_ENGINE

存储引擎设置

-DSYSCONFDIR

mysql配置文件my.cnf地址默认/etc下

-DMYSQL_TCP_PORT

数据库服务器TCP/IP连接的监听端口默认为3306

-DEXTRA_CHARSETS

-DDEFAULT_CHARSET

-DDEFAULT_COLLATION

数据库编码设置

-DENABLED_LOCAL_INFILE

默认为关闭这里开启

-DWITH_DEBUG

DEBUG开关,默认为关

5、下载安装uWsgi

  1. # wget http://projects.unbit.it/downloads/uwsgi-1.2.3.tar.gz
  2. #
  3. # tar xvfz uwsgi-1.2.3.tar.gz
  4. # cd uwsgi-1.2.3
  5. # python uwsgiconfig.py --build

二、配置篇

1、配置nginx(配置nginx.conf)

  1. server {
  2. listen 8080;
  3. server_name django;
  4.  
  5. location / {
  6. root /data/htdocs/django;
  7. include uwsgi_params;
  8. uwsgi_pass 127.0.0.1:8000;
  9. }
  10.  
  11. access_log /data/htdocs/django/access.log;
  12. }

2、配置uWsgi

可以将uwsgi的配置文件做成ini格式的,也可以直接在命令行进行输入,下面给出了ini文件形式的配置

  1. #uwsgi.ini
  2. [uwsgi]
  3. socket = 127.0.0.1:8000
  4. file=/data/htdocs/django/django_uwsgi.py
  5. pidfile = /data/htdocs/django/django_uwsgi.pid
  6. master = true
  7. workers = 4
  8. daemonize = /data/htdocs/django/django_uwsgi.log

其中django.py是我们需要自己定义的,它是用来将uwsgi与django进行连接的。

  1. #django_uwsgi.py
  2. #!/usr/bin/python
  3.  
  4. import os, sys
  5. from django.core.handlers.wsgi import WSGIHandler
  6.  
  7. if not os.path.dirname(__file__) in sys.path[:1]:
  8. sys.path.insert(0, os.path.dirname(__file__))
  9.  
  10. os.environ['DJANGO_SETTINGS_MODULE'] = 'mysites.settings'    #设置配置文件
  11.  
  12. application = WSGIHandler()                      #调用django的处理函数WSGIHandler

3、配置mySQL

在安装完成后,创建mysql用户,并将mysql的目录拥有者换成mysql和mysql所属的group,并设置数据库的用户名和data的路径。

  1. # groupadd mysql
  2. # useradd -g mysql mysql
  3. # chown mysql.mysql -R /service/mysql/
  4. # /usr/local/mysql/scripts/mysql_install_db --user=mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data

将配置文件拷贝到/etc/下,并重命名为my.conf

  1. # cp /usr/local/mysql/support-files/my-medium.cnf /etc/my.cnf

4、配置Django连接MySQL

在安装完成后,需要创建运行环境

  1. # python manage.py startproject

执行后,会在创建一个文件manage.py和一个目录mysite,mysite目录中有urls.py,__init__.py,settings.py和wsgi.py文件。我们通过修改settings.py文件中的部分配置来连接mysql数据库。

假设在mysql中,创建了一个数据库test_python,并添加了一个用户名python_user且密码为python_user,而我们连接地 址为192.168.1.2的mysql服务器,端口为3306(默认),则更改settings.py如下:

  1. ...
  2. DATABASES = {
  3. 'default': {
  4. 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
  5. 'NAME': 'test_python', # Or path to database file if using sqlite3.
  6. 'USER': 'python_user', # Not used with sqlite3.
  7. 'PASSWORD': 'python_user', # Not used with sqlite3.
  8. 'HOST': '192.168.1.2', # Set to empty string for localhost. Not used with sqlite3.
  9. 'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
  10. }
  11. }
  12. ...

通过django中的manage.py进行验证

  1. # python manage.py shell
  2. >> from django.db import connection
  3. >> cursor = connection.cursor()

如果成功,则表明连接数据库成功,其余的关于django的使用在此不多介绍。

5、配置Django连接MongoDB

这里可以直接使用PyMongo模块,也可以使用第三方的中间件mongoengine,PyMongo使用方法的介绍有很多,可以直接查看官方文档http://api.mongodb.org/python/current/api/pymongo/connection.html

这里主要介绍mongoengine的配置方法

首先,要在settings中设置一个包含数据库信息的别名,在连接时会用到

  1. DATABASES = {
  2. ...
  3. 'MongoDB': {
  4. 'ENGINE': 'django_mongodb_engine',
  5. 'NAME':'test',
  6. }
  7. }
  8. ...

其中NAME指的是database的名字。

如果你想使用 django 的 session 和 authentication 这两个框架, 还要加入

  1. # add session
  2. SESSION_ENGINE = 'mongoengine.django.sessions'
  3.  
  4. # add authentication
  5. AUTHENTICATION_BACKENDS = ('mongoengine.django.auth.MongoEngineBackend',
  6. )

然后就可以使用mongoengine了。

  1. from mongoengine import *
  2. from mysite.settings import DATABASES
  3. conn = connect('MongoDB', ip="127.0.0.1", port=27017)

这里使用了settings中定义的别名'MongoDB'。

三、启动篇

1、启动Django服务

启动Django服务进程

  1. # python manage.py runserver 0.0.0.0:8000

2、启动mongoDB服务进程

  1. # /usr/local/mongodb/bin/mongod --port=27000 --dbpath=$HOME/data/ --logpath=$HOME/data/mongo.log

3、启动mysql服务

  1. # /etc/init.d/mysqld start

四、实例篇

1、通过django的模板和mysql数据库中的数据,生成一个包含人名及信息表格的html页面

首先,我们先在数据库中建立一个表peoples,并插入三条数据

  1. mysql> create table peoples (id int auto_increment primary key, name char(30), age int, birth date);
  2. mysql>
  3. mysql> insert into peoples(name, age, birth) values('zhangsan', 30,' 1983-1-1'),('lisi', 29, '1984-1-1'), ('wangwu', 28, '1985-1-1');

然后做一个html页面模板,名为peoples_list.html,内容如下:

  1. <html>
  2. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  3. <head>Peoples List</head>
  4. <body>
  5. <br><br>
  6. <table border="1">
  7. <tr>
  8. <th>Name</th><th>Age</th><th>Birth</th>
  9. </tr>
  10. {% for people in peoples_list %}
  11. <tr>
  12. <td>{{ people.0 }}</td>
  13. <td>{{ people.1 }}</td>
  14. <td>{{ people.2 }}</td>
  15. </tr>
  16. {% endfor %}
  17. </table>
  18. </body>
  19. </html>

接下来是完成业务逻辑,保存在文件peoples.py中(使用了django自带的数据库管理模块)

  1. #!/bin/python
  2.  
  3. #!/bin/python2
  4. # -*- coding: utf-8 -*-
  5.  
  6. from django.db import connection
  7. from django.shortcuts import render_to_response
  8.  
  9. def peoples_list(request):
  10. cursor = connection.cursor()
  11. cursor.execute('select name,age,birth from peoples')
  12. peoples = cursor.fetchall()
  13. return render_to_response('peoples_list.html', {'peoples_list':peoples})

最后修改urls.py中的配置,标红的就是修改的内容

  1. from django.conf.urls import patterns, include, url
  2.  
  3. from peoples import peoples_list
  4.  
  5. # Uncomment the next two lines to enable the admin:
  6. # from django.contrib import admin
  7. # admin.autodiscover()
  8.  
  9. urlpatterns = patterns('',
  10. # Examples:
  11. # url(r'^$', 'mysite.views.home', name='home'),
  12. # url(r'^mysite/', include('mysite.foo.urls')),
  13.  
  14. # Uncomment the admin/doc line below to enable admin documentation:
  15. # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
  16.  
  17. # Uncomment the next line to enable the admin:
  18. # url(r'^admin/', include(admin.site.urls)),
  19. url(r'peoples_list/$', peoples_list),
  20. )

通过浏览器访问对应的地址就能看到最终的结果

2、使用MySQLdb来完成上面的业务逻辑

业务逻辑保存在peoples_mysqldb.py中

  1. #!/bin/python
  2. # -*- coding: utf8 -*-
  3.  
  4. from django.shortcuts import render_to_response
  5. import MySQLdb
  6.  
  7. def peoples_list_mysqldb(request):
  8. conn = MySQLdb.connect(host='127.0.0.1', port=3306, user='python_user', passwd='python_user', db='test_python', charset='utf8')
  9. cursor = conn.cursor()
  10. sqlComm = "select name, age, birth from peoples"
  11. cursor.execute(sqlComm)
  12. peoples = cursor.fetchall()
  13. cursor.close()
  14. conn.close()
  15. return render_to_response('peoples_list.html', {'peoples_list':peoples})

修改urls.py

  1. from django.conf.urls import patterns, include, url
  2.  
  3. #from view import current_datetimefrom peoples_mysqldb import peoples_list_mysqldb
  4.  
  5. # Uncomment the next two lines to enable the admin:
  6. # from django.contrib import admin
  7. # admin.autodiscover()
  8.  
  9. urlpatterns = patterns('',
  10. # Examples:
  11. # url(r'^$', 'mysite.views.home', name='home'),
  12. # url(r'^mysite/', include('mysite.foo.urls')),
  13.  
  14. # Uncomment the admin/doc line below to enable admin documentation:
  15. # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
  16.  
  17. # Uncomment the next line to enable the admin:
  18. # url(r'^admin/', include(admin.site.urls)),
  19. url(r'peoples_list_mysqldb/$', peoples_list_mysqldb)
  20. )

最终的结果为:

3、将数据库数据以json形式返回

主要是业务逻辑代码的编写:test_json.py

  1. # coding: utf-8
  2. #!/bin/python
  3.  
  4. from django.utils import simplejson
  5. from django.http import HttpResponse
  6. from django.db import connection
  7.  
  8. def json_peoples(request):
  9. cursor = connection.cursor()
  10. cursor.execute('select name, age, birth from peoples')
  11. peoples = cursor.fetchall()
  12. i = 0
  13. json_peoples = {}
  14. names = locals()
  15. for people in peoples:
  16. tag = 'person%s' % i
  17. names[tag] = {'name':people[0], 'age':people[1], 'birth':str(people[2])}
  18. json_peoples[tag] = names[tag]
  19. i = ((i+1))
  20.  
  21. json = {'person':i}
  22.  
  23. json['person_info'] = json_peoples
  24. cursor.close()
  25.  
  26. return HttpResponse(simplejson.dumps(json, ensure_ascii=False, sort_keys=True))

向urls中添加该对应关系

  1. from django.conf.urls import patterns, include, url
  2.  
  3. #from view import current_datetime
  4. from json_test import json_peoples
  5.  
  6. # Uncomment the next two lines to enable the admin:
  7. # from django.contrib import admin
  8. # admin.autodiscover()
  9.  
  10. urlpatterns = patterns('',
  11. # Examples:
  12. # url(r'^$', 'mysite.views.home', name='home'),
  13. # url(r'^mysite/', include('mysite.foo.urls')),
  14.  
  15. # Uncomment the admin/doc line below to enable admin documentation:
  16. # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
  17.  
  18. # Uncomment the next line to enable the admin:
  19. # url(r'^admin/', include(admin.site.urls)),
  20. url(r'peoples_json/$', json_peoples)
  21. )

最终效果为:

4、通过pymongo模块访问mongodb,将结果返回成一个页面

模板还是使用第一个例子的,只要重新写一个业务逻辑即可mongodb_test.py

  1. #!/bin/python2
  2. # -*- coding: utf-8 -*-
  3.  
  4. from django.db import connection
  5. from django.shortcuts import render_to_response
  6.  
  7. def peoples_list(request):
  8. cursor = connection.cursor()
  9. cursor.execute('select name,age,birth from peoples')
  10. peoples = cursor.fetchall()
  11. print peoples
  12. return render_to_response('peoples_list.html', {'peoples_list':peoples})

向urls.py中添加对应关系

  1. from django.conf.urls import patterns, include, url
  2.  
  3. #from view import current_datetime
  4. from mongodb_test import mongodb_peoples
  5.  
  6. # Uncomment the next two lines to enable the admin:
  7. # from django.contrib import admin
  8. # admin.autodiscover()
  9.  
  10. urlpatterns = patterns('',
  11. # Examples:
  12. # url(r'^$', 'mysite.views.home', name='home'),
  13. # url(r'^mysite/', include('mysite.foo.urls')),
  14.  
  15. # Uncomment the admin/doc line below to enable admin documentation:
  16. # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
  17.  
  18. # Uncomment the next line to enable the admin:
  19. # url(r'^admin/', include(admin.site.urls)),
  20. url(r'peoples_mongo/$', mongodb_peoples)
  21. )

最终结果为

五、性能

由于系统中有nginx,uwsgi,django,mysql和mongodb模块,所以分别对几种情况下做了一下简单的性能测试。

测试工具使用了SuperWebBench,具体介绍可以查看http://www.oschina.net/p/superwebbench上的介绍。

测试环境:2核Intel(R) Xeon(R) CPU E5645,4G内存,上述所有模块在一台服务器上运行。

采用了并发500,持续30秒的测试压力。

测试nginx:

  1. ./superwebbench -c 500 -t 30 http://127.0.0.1:8000/
  2.  
  3. SuperWebBench - Advanced Simple Web Benchmark 0.1
  4. Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
  5. Modified By Davelv 2011-11-03
  6.  
  7. Benchmarking:GET http://127.0.0.1:8000/ (using HTTP/1.1)
  8.  
  9. 500 clients, running 30 sec.
  10.  
  11. Speed=6080 pages/sec, 4998280 bytes/sec.
  12. Requests: 182419 ok, 0 http error, 0 failed.

测试nginx+uwsgi:(将uwsgi的文件指向一个直接返回http响应的python脚本)

用于返回包含当前时间的HTML页面的Python脚本:

  1. # coding: utf-8
  2. #!/usr/local/bin/python
  3.  
  4. import datetime
  5.  
  6. def application(environ, start_response):
  7. cur = datetime.datetime.now()
  8. response_body = """<html>
  9. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  10. <head>Current Datetime</head>
  11. <body>It is now %s</body>
  12. </html>""" % cur
  13. status = '200 OK'
  14. response_headers = [('Content-Type', 'text/plain'), ('Content-Length', str(len(response_body)))]
  15.  
  16. start_response(status, response_headers)
  17. return [response_body]

结果:

  1. ./superwebbench -c 500 -t 30 http://127.0.0.1:8000/
  2.  
  3. SuperWebBench - Advanced Simple Web Benchmark 0.1
  4. Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
  5. Modified By Davelv 2011-11-03
  6.  
  7. Benchmarking:GET http://127.0.0.1:8000/ (using HTTP/1.1)
  8.  
  9. 500 clients, running 30 sec.
  10.  
  11. Speed=4417 pages/sec, 1351734 bytes/sec.
  12. Requests: 132523 ok, 0 http error, 0 failed.

测试nginx+uwsgi+mysql:

用于返回包含mysql数据的HTML页面的Python脚本:

  1. # coding: utf-8
  2. #!/usr/local/bin/python
  3.  
  4. import datetime
  5. import MySQLdb
  6.  
  7. def application(environ, start_response):
  8. conn = MySQLdb.connect(host='127.0.0.1', port=3306, user='python_user', passwd='python_user', db='test_python', charset='utf8')
  9. cursor = conn.cursor()
  10. sqlComm = "select name, age, birth from peoples"
  11. cursor.execute(sqlComm)
  12. peoples = cursor.fetchall()
  13. cursor.close()
  14. conn.close()
  15. body = "<table border=\"1\"><tr><th>Name</th><th>Age</th><th>Birth</th></tr>"
  16. for people in peoples:
  17. person = "<tr><td>%s</td><td>%s</td><td>%s</td></tr>" % (str(people[0]), str(people[1]), str(people[2]))
  18. body = body + person
  19. body = body +"</table>"
  20. response_body = """<html>
  21. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  22. <head>People List</head>
  23. <body>%s</body></html>""" % body
  24.  
  25. status = '200 OK'
  26. print response_body
  27. response_headers = [('Content-Type', 'text/plain'), ('Content-Length', str(len(response_body)))]
  28. print response_headers
  29. start_response(status, response_headers)
  30. return [response_body]

结果

  1. ./superwebbench -c 500 -t 30 http://127.0.0.1:8000/
  2.  
  3. SuperWebBench - Advanced Simple Web Benchmark 0.1
  4. Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
  5. Modified By Davelv 2011-11-03
  6.  
  7. Benchmarking:GET http://127.0.0.1:8000/ (using HTTP/1.1)
  8.  
  9. 500 clients, running 30 sec.
  10.  
  11. Speed=1078 pages/sec, 539381 bytes/sec.
  12. Requests: 32345 ok, 13 http error, 0 failed.

测试nginx+uwsgi+django:

  1. ./superwebbench -c 500 -t 30 http://127.0.0.1:8000/time/
  2.  
  3. SuperWebBench - Advanced Simple Web Benchmark 0.1
  4. Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
  5. Modified By Davelv 2011-11-03
  6.  
  7. Benchmarking:GET http://127.0.0.1:8000/time/ (using HTTP/1.1)
  8.  
  9. 500 clients, running 30 sec.
  10.  
  11. Speed=652 pages/sec, 176182 bytes/sec.
  12. Requests: 19558 ok, 7 http error, 0 failed.

测试nginx+uwsgi+django+mysql:

  1. ./superwebbench -c 500 -t 30 http://127.0.0.1:8000/peoples_list/
  2.  
  3. SuperWebBench - Advanced Simple Web Benchmark 0.1
  4. Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
  5. Modified By Davelv 2011-11-03
  6.  
  7. Benchmarking:GET http://127.0.0.1:8000/peoples_list/ (using HTTP/1.1)
  8.  
  9. 500 clients, running 30 sec.
  10.  
  11. Speed=321 pages/sec, 204044 bytes/sec.
  12. Requests: 9615 ok, 23 http error, 0 failed.

测试nginx+uwsgi+django+mongodb:

  1. ./superwebbench -c 500 -t 30 http://127.0.0.1:8000/peoples_mongo/
  2.  
  3. SuperWebBench - Advanced Simple Web Benchmark 0.1
  4. Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
  5. Modified By Davelv 2011-11-03
  6.  
  7. Benchmarking:GET http://127.0.0.1:8000/peoples_mongo/ (using HTTP/1.1)
  8.  
  9. 500 clients, running 30 sec.
  10.  
  11. Speed=355 pages/sec, 221449 bytes/sec.
  12. Requests: 10648 ok, 15 http error, 0 failed.

总结一下,可以看出nginx的处理速度极快,而uwsgi同样也不慢,最大的瓶颈在于django,效率大概下降了70%多,而数据库查询(无论是mysql还是mongodb)也对效率有一定影响。

当然,这只是把所有服务都部署在一台服务器上,对资源的抢占也影响了系统的效率。

六、其它介绍

1、编码问题

需要注意编码问题,否则会出现乱码或者执行错误。

有四个部分需要统一编码格式(以utf8为例):

(1)    mysql数据库的编码设置(charset = ‘utf8’)

(2)    python文件的编码设置(# -*- coding:utf8 -*-)

(3)    连接mysql数据库时要加上参数charset=’utf8’

(4)    如果使用django,则需要在settings.py中添加DEFAULT_CHARSET = 'utf8'。

2Python通过MySQLdbMySQL的操作

导入MySQLdb模块

  1. import MySQLdb

与数据库建立连接

  1. conn=MySQLdb.connect([host="localhost",][port=3306,] user="root", passwd="passwd",db="database_name"[, charset=’utf8’])

其中host为mysql主机名,port为端口号,user为用户名,passwd为密码,db为数据库名,charset为编码类型

获取游标

  1. cursor = conn.cursor()

数据库命令

插入命令

  1. insertComm = insert into table_name(...) values(...)’
  2. cursor.execute(insertComm,...)

如:(注意最后要调用commit来提交这次命令)

  1. insertComm = 'insert into peoples(name, age, birth) values(%s, %s, %s)'
  2. param = ('zhengliu', 27, '1986-1-1')
  3. cursor.execute(insertComm, param)
  4. conn.commit()

更新命令

  1. updateComm = update table_name set column1=value1[,...] where column=value[,...]’
  2. cursor.execute(updateComm)

如:(注意最后要调用commit来提交这次命令)

  1. updateComm = "update peoples set age=%s,birth=%s where name='zhengliu'"
  2. param = (26, '1987-1-1')
  3. cursor.execute(updateComm, param)
  4. conn.commit()

删除命令

  1. deleteComm = delete from table_name where column1=value1[,...]’
  2. cursor.execute(deleteComm)

如:(注意最后要调用commit来提交这次命令)

  1. deleteComm = "delete from peoples where name=%s"
  2. param=('zhengliu')
  3. cursor.execute(deleteComm, param)
  4. conn.commit()

查询命令

  1. selectComm = select name, age, birth from peoples [where column1=values1,...]’
  2. cursor.execute(selectComm)
  3. result = cursor.fetchall()

如:

  1. queryComm = 'select name, age, birth from peoples'
  2. cursor.execute(queryComm)
  3. peoples = cursor.fetchall()

提交和回滚

在对数据库进行修改操作时,需要进行commit命令来最终提交数据库,如果想要取消这次操作,则要在commit前先调用rollback进行回滚操作。

  1. conn.commit()
  2. conn.rollback()

关闭命令

关闭游标

  1. cursor.close()

关闭连接

  1. conn.close()

cursor游标对象属性及方法

属性方法

描述

arraysize

使用fetchmany()方法时一次取出的记录数,默认为1

connection

创建此游标的连接(可选)

discription

返回游标的活动状态,包括(7元素):(name,type_code, display_size,internal_size,precision,scale,null_ok) 其中name,type_code是必须的。

lastrowid

返回最后更新行的ID(可选),如果数据库不支持,返回None

rowcount

最后一次execute()返回或影响的行数

callproc(func[,args])

调用一个存储过程

close()

关闭游标

execute(op[,args])

执行sql语句或数据库命令

executemany(op,args)

一次执行多条sql语句,执行的条数由arraysize给出

fetchone()

匹配结果的下一行

fetchall()

匹配所有剩余结果

fetchmany(size-cursor,arraysize)

匹配结果的下几行

__iter__()

创建迭代对象(可选,参考next())

messages

游标执行好数据库返回的信息列表(元组集合)

next()

使用迭代对象得到结果的下一行

nextset()

移动到下一个结果集(如果支持的话)

rownumber

当前结果集中游标的索引(从0行开始)

setinput-size(sizes)

设置输入最大值

setoutput-size(sizes[,col])

设置列输出的缓冲值

Django+Nginx+MongoDB+Mysql+uWsgi的搭建的更多相关文章

  1. python3环境搭建(uWSGI+django+nginx+python+MySQL)

    1.系统环境,必要知识 #cat /etc/redhat-release CentOS Linux release (Core) #uname -r -.el7.x86_64 暂时关闭防护墙,关闭se ...

  2. linux下nginx+php+mysql 自助环境搭建

    ++++++++++++++++++++++++++++++++++++++++++++++linux下nginx+php+mysql环境搭建+++++++++++++++++++++++++++++ ...

  3. 一个前端博主的nginx+php+mysql的环境搭建

    这几天天某的公司给了在下一个需求,让我修改一个后端大佬用PHP写的一个官网,虽然说修改的内容还是很简单,但是毕竟之前还是没接触过PHP,于是开始了漫长的爬坑之旅,话不多说,这次就给大家介绍一下我配置安 ...

  4. NGINX+PHP+MYSQL服务器环境搭建

    这条命令是配置vim的,请确保你能访问github wget -qO- https://raw.github.com/ma6174/vim/master/setup.sh | sh 说明有一些小问题, ...

  5. CentOS7.X安装LMMP环境Nginx+PHP+Mysql详解

    前言: 作为PHP开发者,我们常用的线上环境就是LNMP,合理的搭建也是必须掌握的技能,下面就利用源码的方式详细介绍下LNMP环境Nginx+PHP+Mysql的详细搭建步骤: 版本说明: Nginx ...

  6. centos6+nginx+php+mysql+memcached+wordpress

    centos6+nginx+php+mysql+memcached+wordpress 搭建步骤(1) LNMP 平台搭建: 请参考:http://www.cnblogs.com/ligao/p/61 ...

  7. 【Ubuntu14】Nginx+PHP5+Mysql记录

    这次因为工作原因,需要在Linux下进行开发.推荐的环境是Ubuntu14+Nginx+PHP+Mysql.环境搭建好之后,装上GIT,装上IDE,觉得Mysql命令界面麻烦又装了个Navicat.总 ...

  8. [转载]CentOS 7 用户怎样安装 LNMP(Nginx+PHP+MySQL)

    关于 Nginx (发音 "engine x")这是一款免费.开源.高效的 HTTP 服务器,Nginx是以稳定著称,丰富的功能,结构简单,低资源消耗.本教程演示如何在CentOS ...

  9. Ubuntu+Django+Nginx+uWSGI+Mysql搭建Python Web服务器

    Ubuntu+Django+Nginx+uWSGI+Mysql搭建Python Web服务器 闲着无聊的时候部署了一个Django项目玩,用vm虚拟机部署的. 准备工作 我使用的系统是Ubuntu16 ...

随机推荐

  1. php添加环境变量

    在php的安装目录中添加,如/usr/php-5.6.16添加env.php文件,在文件中设置环境变量: 如:<?php$_SERVER['ENV'] = 'production'; 再到配置文 ...

  2. 学习练习 java数据库查询小题

    10. 查询Score表中的最高分的学生学号和课程号.(子查询或者排序) 11. 查询每门课的平均成绩. 12.查询Score表中至少有5名学生选修的并以3开头的课程的平均分数. 13.查询分数大于7 ...

  3. cocos2dx 内存管理机制

    持续更新吧. 刚开始看了一些. 一,CCObject  提供引用计数 1,unsinged int m_uReference; //此为CCOBject的引用计数,初始化为 1: new CCObje ...

  4. 关于BitmapFactory解析流的问题a

    今天碰到了一个超级恶心的问题,BitmapFactory.decodeStream(bis,null,options)一直是返回NULL 问题是这样子的: InputStream is= respon ...

  5. [前端 4] 使用Js实现图片上传预览

    导读:今天做图片上传预览,刚开始的做法是,先将图片上传到Nginx,然后重新加载页面才能看到这个图片.在这个过程中,用户一直都看不到自己上传的文件是什么样子.Ps:我发现我真的有强迫症了,都告诉我说不 ...

  6. vyos (一) 基础配置

    http://www.lowefamily.com.au/2015/11/29/using-a-vyos-router-with-hyper-v/1/ http://thomasvochten.com ...

  7. solr5.5教程-solrconfig.xml,加载schema.xml

    布署完成后,接下来要更深入的研究solr的原理和使用. 首先进入testcore这个文件夹下面,发现这个core的conf里并没有schema.xml.那么数据格式是在哪里定义的呢? 打开 solr_ ...

  8. iOS 8.3 JB ready

    Hi, I've been waiting for a very very long time..Now iOS 8.3 is ready. http://www.taig.com/ You guys ...

  9. Spring web Flow2学习笔记

    想抽时间研究一下Spring web Flow2,能够找到的唯一电子书是<深入解析Spring+MVC与Web Flow>,我现在摘录本书的一段内容如下,通过这一段,大家可以想象中文背景的 ...

  10. 搭建高性能计算环境(七)、应用软件的安装之MS

    1,上传软件包MaterialsStudio70.tgz.msi_7.lic到服务器上. 2,安装ms一般会创建一个普通用户msi,软件安装在msi账号下. 创建用户msi: useradd msi ...