uWSGI介绍
uWSGI是一个Web服务器,它实现了WSGI协议、uwsgi、http等协议。Nginx中HttpUwsgiModule的作用是与uWSGI服务器进行交换。
要注意 WSGI / uwsgi / uWSGI 这三个概念的区分。
- WSGI是一种Web服务器网关接口。它是一个Web服务器(如nginx,uWSGI等服务器)与web应用(如用Flask框架写的程序)通信的一种规范。
- uwsgi是一种线路协议而不是通信协议,在此常用于在uWSGI服务器与其他网络服务器的数据通信。
- 而uWSGI是实现了uwsgi和WSGI两种协议的Web服务器。
- uwsgi协议是一个uWSGI服务器自有的协议,它用于定义传输信息的类型(type of information),每一个uwsgi packet前4byte为传输信息类型描述,它与WSGI相比是两样东西。
uWSGI的速度非常快,普通的电脑都能承受每秒两千多次的并发访问。
uWSGI的使用
通过pip安装过之后,使用命令去执行一个py文件:
uwsgi --http:8000 --wsgi-file mytest.py
启动django:
uwsgi --http:8000 --module mysite.wsgi # 在每一个django项目中都有一个wsgi文件。
需要的配置的参数写在一个ini文件中,自己vim一个文件然后放在django的主目录中。然后使用命令:
uwsgi thatfile.ini
配置文件内容:
1 [uwsgi] 2 http = :9000 3 #the local unix socket file than commnuincate to Nginx 4 socket = 127.0.0.1:8001 # 这里是和Nginx进行通信的地址,一般为本机, 因为两个程序运行在一个服务器中。 5 # the base directory (full path) 6 chdir = /home/ccc/DelightRobin 7 # Django's wsgi file 8 wsgi-file = DelightRobin/wsgi.py 9 # maximum number of worker processes 10 processes = 4 # 开多少进程 11 #thread numbers startched in each worker process 12 threads = 2 # 每个进程开多少线程 13 14 #monitor uwsgi status 15 stats = 127.0.0.1:9191 # uwsgi提供监控的端口 16 # clear environment on exit 17 vacuum = true
这里解释一下三者没什么要配合着使用:在django中提供的并发的测试模式只适用于测试用(承担并发小,速度慢,容易down。)。同时,uwsgi也能直接运行保证django程序的运行。Nginx的作用据说是大家都这么用。Nginx的主要作用是接收到client的信息后给uwsgi,还有静态文件的获取。
Nginx安装和使用
apt-get 安装好Nginx之后,试着启动去init.d下Nginx start服务。输入本机地址已经出来欢迎页面了。
但是如果想要自己的django启动还要配置一个文件:mysite_nginx.conf 其中必须以nginx.conf结尾,放在django目录中:
在此之前需要将etc/nginx 下的uwsgi_params文件拷贝到django目录中一份。
1 # mysite_nginx.conf 2 3 # the upstream component nginx needs to connect to 4 upstream django { 5 # server unix:///path/to/your/mysite/mysite.sock; # for a file socket 6 server 127.0.0.1:8001; # for a web port socket (we'll use this first) 这里就是uwsgi配置中写的地址 两者通信 7 } 8 9 # configuration of the server 10 server { 11 # the port your site will be served on 12 listen 8000; # 用户端口 13 # the domain name it will serve for 14 server_name .example.com; # substitute your machine's IP address or FQDN 15 charset utf-8; 16 17 # max upload size 18 client_max_body_size 75M; # adjust to taste 19 20 # Django media 21 location /media { 22 alias /path/to/your/mysite/media; # your Django project's media files - amend as required 23 } 24 25 location /static { # 项目静态的文件的地址 26 alias /path/to/your/mysite/static; # your Django project's static files - amend as required 27 } 28 29 # Finally, send all non-media requests to the Django server. 30 location / { 31 uwsgi_pass django; 32 include /path/to/your/mysite/uwsgi_params; # the uwsgi_params file you installed django项目中的params文件 33 } 34 }
同时做一个ln -s 的操作将这个配置文件软连接到nginx/sites-enabled 中保证nginx知道项目的存在,因为nginx不单单能支持一个项目的启动。
最后在django中,因为不同的app存在着不同的静态文件,可能导致admin中的静态文件找不到。所以通过manage.py执行复制命令。
Python3 manage.py collectstatic
在此之前先在django的settings文件中写入路径 STATIC_ROOT = 'allfile' 并且保证其他app静态文件不能是同名的。此静态文件才是最后配置在nginx配置文件中的路径文件。