概述
文章是uwsgi关于django部署的学习笔记,过程中涉及:
- 浏览器
- nginx服务器
- linux socket
- uwsgi服务
- django应用
最终各个组件之间的关系是
浏览器 <-> nginx服务器 <-> linux socket <-> uwsgi服务 <-> Django应用
- 当浏览器访问web页面时,如果请求的是静态文件,或者是纯粹html代码是直接从nginx服务器读取就可以了
- 当请求的是django应用中内容的话,浏览器发生请求时,经过nginx服务器的中转,将请求交给uwsgi进行处理,而uwsgi最终调用django中的具体处理函数进行处理,得到响应,一层层返回给浏览器
验证uwsgi和python之间的交互
首先,创建一个test.py文件用来处理来自浏览器的请求,内容如下:
# test.py
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello World"] # python3
#return ["Hello World"] # python2
其次,启动uwsgi,并指定test.py进行请求处理
uwsgi --http :8000 --wsgi-file test.py
最后,打开浏览器,请求http://localhost:8000页面,如果可以看到Hello World的话,说明浏览器 <----> uwsgi服务 <----> python应用
这个通道是顺畅的。
验证uwsgi和django之间的交互
首先,创建django项目,比如叫mysite。 其次,启动uwsgi,并指定由mysite.wsgi文件处理请求
uwsgi --http :8000 --module mysite.wsgi
最后,打开浏览器访问http://localhost:8000页面,如果一切正常的话,访问到的应该是django经典的It worked页面了。如果看到的话,说明浏览器 <----> uwsgi服务 <----> django应用
这个通道是同样是顺畅的.
配置ngnix提供django中静态文件的处理
首先,配置nginx使用8000端口,处理/media和/static的请求,其他请求一律交给uwsgi启动的8001端口处理.
# configuration of the server
server {
# the port your site will be served on
listen 8000;
# the domain name it will serve for
server_name .example.com; # substitute your machine's IP address or FQDN
charset utf-8;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media
location /media {
alias /path/to/your/mysite/media; # your Django project's media files - amend as required
}
location /static {
alias /path/to/your/mysite/static; # your Django project's static files - amend as required
}
# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass http://localhost:8001;
include uwsgi_params;
}
}
其次,在mysite中的settings.py文件中进行如下配置
STATIC_ROOT=os.path.join(BASE_DIR, 'static')
STATIC_URL='/static/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
执行python manage.py collectstatic
将所有的静态文件收集到指定的位置.
最后,打开浏览器,访问http://localhost:8000/static/js/jquery.min.js。如果一切正常的话,会看到jquery文件,说明nginx已经可以处理用户对静态文件的请求了.
终极整合
首先,使用上面的nginx配置。 其次,使用uwsgi启动django应用
uwsgi --http :8001 --module mysite.wsgi
最后,打开浏览器访问http://localhost:8000,将出现django的it worked,访问http://localhost:8000/static/js/jquery.min.js会出现jquery文件.
更高级的使用方法
-
使用socket代替http,并使用uwsgi配置文件
# mysite_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /path/to/your/project # Django's wsgi file module = project.wsgi # the virtualenv (full path) home = /path/to/virtualenv # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket = /path/to/your/project/mysite.sock # ... with appropriate permissions - may be needed # chmod-socket = 664 # clear environment on exit vacuum = true
-
将uwsgi设置为开机自启动
# /etc/rc.local /usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data --daemonize /var/log/uwsgi-emperor.log exit 0
来源:oschina
链接:https://my.oschina.net/u/1275007/blog/628573