一、Django配置

1. 创建一个新项目

django-admin.py startproject mysite

2. 创建一个应用

python3 startapp app01

3. 编辑urls.py文件,创建一个index页面路由

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
]

4. 编辑views.py文件,创建视图函数

def index(request):
    return render(request, "index.html")

5. 在项目目录下创建templates目录,以及index.html文件

<html>
	<head>
		<meta charset="UTF-8">
		<title>index</title>
	</head>
	<body>
		<h2>uWSGI页面</h2>
		<img src="/static/02.jpg"/>
	</body>
</html>

6. 在项目目录下创建static目录,将02.jpg文件放进去。

由于我们这次使用uWSGI和Nginx,所以不用在setting.py文件配置静态文件路径。


二、安装配置uWSGI

1. 安装uWSGI

pip install uwsgi

2. 测试uWSGI服务器

# test.py
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"]
uwsgi --http :9090 --wsgi-file test.py

访问”http://127.0.0.1:9090“,如果出现"Hello World"则表示uWSGI安装成功

3. 在Django项目目录mysite/app01目录下创建一个uwsgi.ini文件

[uwsgi]

# 配置服务器IP地址和端口
http = 127.0.0.1:3309

# 配置项目目录
chdir = /script/PycharmProjects/mysite

# 配置入口模块
wsgi-file = mysite/wsgi.py

# 开启master
master = True

# 设置worker进程数量
processes = 2

# 服务器进程开启的线程数量
threads = 4

# 退出清空环境变量
vacuum = True

# 进程pid
pidfile = uwsgi.pid

# 配置静态文件目录
check-static = /script/PycharmProjects/mysite

4. 启动uWSGI服务器提供静态页面和动态页面访问

uwsgi --ini uwsgi.ini

5. 访问"http://127.0.0.1:3309/index/",如果出现文件以及图片则表示设置成功

6. 修改uwsgi.ini文件,动态文件留给uWSGI处理,静态文件给Nginx处理

[uwsgi]

# 配置服务器IP地址和端口
#http = 127.0.0.1:3309
socket = 127.0.0.1:3309

# 配置项目目录
chdir = /script/PycharmProjects/mysite

# 配置入口模块
wsgi-file = mysite/wsgi.py

# 开启master
master = True

# 设置worker进程数量
processes = 2

# 服务器进程开启的线程数量
threads = 4

# 退出是清空环境变量
vacuum = True

# 进程pid
pidfile = uwsgi.pid

# 配置静态文件目录
#check-static = /script/PycharmProjects/mysite


三、安装配置Nginx

1. 安装Nginx

tar -zxvf nginx-1.10.2.tar.gz
cd nginx-1.10.2
./configure

2. 环境检查缺失pcre包,安装libpcre3和libpcre3-dev

sudo apt-get install libpcre3 libpcre3-dev

3. 环境检查缺失zlib包,从http://www.zlib.net下载最新软件包并安装

tar -zxvf zlib-1.2.11.tar.gz
cd zlib-1.2.11
./zlib-1.2.11
make
sudo make install

4. 配置使用openssl,从https://www.openssl.org/source/下载最新软件包,并解压

tar -zxvf openssl-1.0.2l.tar.gz

5. 重新运行Nginx configure文件

./configure --with-openssl=/Download/openssl-1.0.2l --with-http_ssl_module

6. 检查无误,编译安装

make
sudo make install

7. 配置Nginx,动态文件转给uWSGI处理,静态文件自己处理

默认配置文件路径:/usr/local/nginx/conf/nginx.conf

location / {
	include uwsgi_params;
	uwsgi_pass 127.0.0.1:3309;
}	

location /static {
	alias /script/PycharmProjects/mysite/static;
}

8. Nginx启停命令

cd /usr/local/nginx/sbin
sudo ./nginx  # 启动
sudo ./nginx -s stop  # 停止
sudo ./nginx -s reload  # 重新加载配置文件

9. 现在我们把uWSGI和Nginx一起启动,并访问http://127.0.0.1/index/,如果出现文字和图片说明我们已经配置成功了!