一:服务器环境配置
- 在本地的虚拟环境中,项目根目录下,执行命令收集所有包
pip freeze > plist.txt
- 通过xftp软件将开发好的项目和收集的包上传到服务器某个目录
- 在服务器上面安装并创建虚拟环境,如果已有则跳过此步
sudo apt-get install python-virtualenv
sudo apt-get install virtualenvwrapper
mkvirtualenv -p /usr/bin/python3 [虚拟环境名称]
- 在虚拟环境上工作,安装所有需要的包,cd到plist.txt所在的目录。一般把txt放在项目里面去,直接cd到项目目录
workon [虚拟环境名称]
pip install -r plist.txt
- 更改服务器里面的settings.py文件
DEBUG = False
ALLOW_HOSTS=['*',]表示可以访问服务器的ip
- 在服务器虚拟环境里面安装uWSGI
- python manage.py runserver:这是一款适合开发阶段使用的服务器,不适合运行在真实的生产环境中
- 在生产环境中使用WSGI
- WSGI:Web服务器网关接口,英文为Python Web Server Gateway Interface,缩写为WSGI,是Python应用程序或框架和Web服务器之间的一种接口,被广泛接受
- WSGI没有官方的实现, 因为WSGI更像一个协议,只要遵照这些协议,WSGI应用(Application)都可以在任何服务器(Server)上运行
- 命令django-admin startproject会生成一个简单的wsgi.py文件,确定了settings、application对象
- application对象:在Python模块中使用application对象与应用服务器交互
- settings模块:Django需要导入settings模块,这里是应用定义的地方
- 此处的服务器是一个软件,可以监听网卡端口、遵从网络层传输协议,收发http协议级别的数据
-
uWSGI
- uWSGI实现了WSGI的所有接口,是一个快速、自我修复、开发人员和系统管理员友好的服务器
- uWSGI代码完全用C编写
- 安装uWSGI
sudo pip install uwsgi
- 配置uWSGI,在项目中新建文件uwsgi.ini,编写如下配置
[uwsgi]
socket=外网ip:端口(使用nginx连接时,使用socket)如180.76.57.47:8000
http=外网ip:端口(直接做web服务器,使用http)
chdir=项目根目录
wsgi-file=项目中wsgi.py文件的目录,相对于项目根目录
processes=4 开启4个进程
threads=2 一个进程开启2个线程
master=True
pidfile=uwsgi.pid 运行uwsgi的pid号
daemonize=uswgi.log 记录日志
- 启动:uwsgi --ini uwsgi.ini
- 停止:uwsgi --stop uwsgi.pid
- 重启:uwsgi --reload uwsgi.pid
在virtualenv虚拟环境下pip install uwsgi可能会报错,
Command "/home/windblow/Desktop/windcontrlenv/bin/python3.5 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-_yknw2vb/uwsgi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-w10pyemd-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/windblow/Desktop/windcontrlenv/include/site/python3.5/uwsgi" failed with error code 1 in /tmp/pip-build-_yknw2vb/uwsgi/
原因是缺少【python3.5-dev】,首先安装 sudo apt-get install python3.5-dev
接着在虚拟环境下pip install uwsgi,就可以了
nginx
- 使用nginx的作用
- 负载均衡:多台服务器轮流处理请求
- 反射代理:隐藏真实服务器
- 实现构架:客户端请求nginx,再由nginx请求uwsgi,运行django框架下的python代码
- nginx+uwsgi也可以用于其它框架的python web代码,不限于django
- 到官网下载nginx压缩文件或通过命令安装
sudo apt-get nginx
- 默认安装到/etc/nginx目录,进入此目录执行命令
- 启动:sudo nginx
- 停止:sudo nginx -s stop
- 重启:sudo nginx -s reload
- 通过浏览器查看nginx运行结果
- 指向uwsgi项目:编辑/etc/nginx/sites-ena'b'led/default
在server下添加新的location项,指向uwsgi的ip与端口 listen 80 监听端口,默认为80端口,这样客户端就不需要刻意去输入端口号 server_name 在这里填写客户端访问的ip或域名,如180.76.57.47 www.yimazhuisu.com location / { include uwsgi_params;将所有的参数转到uwsgi下 uwsgi_pass uwsgi的ip与端口 如180.76.57.47:8000; }
location /static{ alias /var/www/BarcodeSystem/static/; }
静态文件
- 所有的静态文件都会由nginx处理,不会将请求转到uwsgi
- 在服务器上创建目录结构“/var/www/BarcodeSystem/”
- 修改目录权限,是目录可以有读写的权限
sudo chmod 777 /var/www/BaecodeSystem
- 接着在创建static目录
mkdir static
- 修改settings.py文件
STATIC_ROOT='/var/www/test5/static/'
- 收集所有静态文件到static_root指定目录:python manage.py collectstatic
- 重启nginx、uwsgi