使用uwsgi部署Django应用

一、打包Django应用

1.创建setup.py文件

from setuptools import setup
import glob

setup(name='blog',
      version='1.0',
      description='blog project',
      author='Keith',
      author_email='329640305@qq.com',
      url='https://www.python.org/',
      packages=['blog', 'user', 'post'],
      py_modules=['manage'],
      data_files=glob.glob('templates/*.html') + ['requirements']
      )

2.保存项目中使用的库

pip freeze > requirements

3.打包源码

python3 setup.py sdist

二、在部署server上安装依赖包

pip3 install -r requirements

三、修改Django配置文件

sed -i -e 's/DEBUG.*/DEBUG = False/' -e 's/ALLOWED_HOSTS.*/ALLOWED_HOSTS = ["*"]/' blog/settings.py

四、测试运行

python3 manage.py runserver 0.0.0.0:8001

第一种部署方式,直接以http方式启动

1.安装uwsgi

pip3 install uwsgi

2.运行app

uwsgi --http :8001 --wsgi-file blog/wsgi.py --stats :8002 --stats-http

3.测试访问
http://ip:8001/post/?page=1&size=2

4.查看server状态
http://ip:8002/


第二种部署方式,提供配置文件,以socket方式运行

1.创建配置文件blog.ini,放在项目根目录下

[uwsgi]
socket = 127.0.0.1:8001
chdir = /opt/blog-1.0/
wsgi-file = blog/wsgi.py
master = true
workers = 3
stats = 127.0.0.1:8002
stats-http = true

2.运行app

uwsgi blog.ini

第三种部署方式,使用systemd管理uwsgi

1.创建service文件

vim /usr/lib/systemd/system/blog.service

[Unit]
Description=uWSGI Emperor
After=syslog.target

[Service]
ExecStart=/usr/local/bin/uwsgi --ini /opt/blog-1.0/blog.ini
# Requires systemd version 211 or newer
RuntimeDirectory=uwsgi   # 会创建/var/run/uwsgi目录
Restart=always
KillSignal=SIGQUIT
Type=notify
StandardError=syslog
NotifyAccess=all

[Install]
WantedBy=multi-user.target

2.启动服务

systemctl start blog.service
systemctl status blog.service
systemctl enable blog.service

还有一个重要的部分,那就是提供Nginx代理

1、安装tengine,很简单,过程略...

2、修改Nginx配置

server {
      listen       80;
      server_name  localhost;

      # http代理
      # location ^~ /api/ {
      #     rewrite ^/api(/.*) $1 break;
      #     proxy_pass http://127.0.0.1:8001;
      # }

      # socket代理
      location ^~ /api/ {
          rewrite ^/api(/.*) $1 break;
          include uwsgi_params;
          uwsgi_pass 127.0.0.1:8001;
      }

      # 根路径,通常是前端SPA单页面应用的入口
      location / {
          root   html;
          index  index.html index.htm;
      }
}

3、启动Nginx服务


到这里,后端应用基本部署完成。
再把前端文件部署好,通过Nginx动静分离就完整了,这里就不说前端应用了。

另外,还有一种常见的部署方式,就是通过supervisord等这类进程管理服务来运行app,这里也不细说了。

参考:
https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html#deploying-django
https://uwsgi-docs.readthedocs.io/en/latest/StatsServer.html
https://uwsgi-docs.readthedocs.io/en/latest/Systemd.html
https://uwsgi-docs.readthedocs.io/en/latest/Configuration.html
http://nginx.org/en/docs/http/ngx_http_uwsgi_module.html

posted @ 2018-12-27 03:19  KeithTt  阅读(1626)  评论(0编辑  收藏  举报