uWSGI + Nginx配置Django项目(一)

来源:互联网 发布:手机淘宝怎样删除订单 编辑:程序博客网 时间:2024/05/18 02:00

uWSGI是一个web服务器, 它实现了uwsgi、wsgi、http协议. uwsgi协议是一个uWSGI服务器自有的协议.django框架自带了wsgiref服务器,为什么我们需要这样的一个服务器呢? wsgiref定位是测试服务器,那么性能,稳定性不能保证。


现在我们将wsgi服务器改成uWSGI web服务器:


安装uWSGI 服务器:

pip install uwsgi

创建python web项目, 目录结构为:

uWSGI_test/
├── wsgi.ini
├── wsgi.log
└── wsgi.py

我们的项目包含两个文件,一个是wsgi.py文件,一个是uWSGI服务器的配置文件wsgi.ini, 这两个文件名都可自定义设置.

其中wsgi.py文件内容如下:

def application(env, start_response):    start_response('200 ok', [('Content-Type', 'text/html')])    return [b'hello uWSGI!']

当客户端(浏览器)发来请求,uWSGI服务器会从我们指定的wsgi入口模块中搜索application函数来执行,函数需要两个参数,env当前请求的环境变量,start_response为返回的响应头信息.

我们下面紧接着对wsgi.ini配置文件进行配置:

[uwsgi]# 配置服务器的监听ip和端口http = 127.0.0.1:3309# 配置项目目录chdir = /home/administrator/PyPros/uWSGI_test# 配置入口模块(/home/administrator/PyPros/uWSGI_test/wsgi.py模块下的application函数为入口函数)module = wsgi:application# 开启master, 将会多开一个管理进程, 管理其他服务进程master = True# 服务器开启的进程数量processes = 2# 服务器进程开启的线程数量threads = 4# 以守护进程方式提供服, 输出信息将会打印到log中# daemonize = wsgi.log# 退出的时候清空环境变量vacuum = true# 进程pidpidfile = uwsgi.pid

启动uWSGI, 并指定加载那个配置文件.

uwsgi --ini wsgi.ini
停止uWSGI, 如果你的配置文件中并没有pidfile = uwssgi.pid配置选项,那么需要使用下面方式停止服务器:

killall -s INT /django_environ/bin/uwsgi
如果您指定了pidfile配置选项,那么可用下面方式停止服务器:

uwsgi --stop uwsgi.pid

运行服务器之后

(django_environ) administrator@ubuntu:~/PyPros/uWSGI_test$ uwsgi --ini wsgi.ini 
[uWSGI] getting INI configuration from wsgi.ini
*** Starting uWSGI 2.0.15 (64bit) on [Mon Sep 18 10:40:31 2017] ***
compiled with version: 5.4.0 20160609 on 17 September 2017 16:52:52
os: Linux-4.4.0-93-generic #116-Ubuntu SMP Fri Aug 11 21:17:51 UTC 2017
nodename: ubuntu
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 2
current working directory: /home/administrator/PyPros/uWSGI_test
writing pidfile to uwsgi.pid
detected binary path: /home/administrator/.virtualenvs/django_environ/bin/uwsgi
chdir() to /home/administrator/PyPros/uWSGI_test
your processes number limit is 19128
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
probably another instance of uWSGI is running on the same address (127.0.0.1:3309).
bind(): Address already in use [core/socket.c line 769]
VACUUM: pidfile removed.


在浏览器中输入 localhost:3309