历时约一周的时间,从一叶障目到一目了然,转载请注明出处,欢迎收藏,评论,点赞,转发哦!
服务器:Linode 2GB: 1 CPU, 50GB Storage, 2GB RAM
系统:CentOS 7
项目:云呗BI系统
工具:Xftp6和Xshell6
软件:pycharm2019.1,Python3.7.4
环境:django2.2.6和vue(3.0版本),nginx和uwsgi最新版本
第一步:django配置
#!settings.py
"""
Django settings for dataAnalysis project.
Generated by 'django-admin startproject' using Django 2.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'u3l9qsl2vp0^ddb2n)h6)&=od_!p7+^4*=t2u+=k&7&%$uoock'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True # 测试的时候看情况给值
ALLOWED_HOSTS = ['173.255.222.190', 'localhost', '0.0.0.0:8000', '127.0.0.1', 'www.cwwage.com']
# ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dataAnalysisApp.apps.DataanalysisappConfig',
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# 开发调试时,实际上是开两个server,一个是8000端口的django server,一个是8080端口的node server
# 增加一行在django层注入header,解决跨域问题
CORS_ALLOW_CREDENTIALS = True # 允许携带cookie
CORS_ORIGIN_ALLOW_ALL = True # 允许所有域名跨域(优先选择)
CORS_ORIGIN_WHITELIST = [] # 白名单
# CORS_URLS_REGEX = r'^.*$'
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'X-Token',
'x-token',
'Pragma',
)
ROOT_URLCONF = 'dataAnalysis.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [os.path.join(BASE_DIR, 'templates')]
'DIRS': [os.path.join(BASE_DIR, "fronted/dist")], #vue打包过来的文件存放路径
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'dataAnalysis.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# REST_FRAMEWORK = {
# # Use Django's standard `django.contrib.auth` permissions,
# # or allow read-only access for unauthenticated users.
# # 'DEFAULT_PERMISSION_CLASSES': [
# # 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
# # ]
# 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
# "PAGE_SIZE": 10,
# }
# DEFAULT_PERMISSION_CLASSES定义权限,只有管理员用户才能访问
# 定义分页条数
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-hans'
# TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
# USE_TZ = True
TIME_ZONE = 'Asia/Shanghai' # 本地时间
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
# 用户上传的文件配置(暂时没有用到)
MEDIA_ROOT = os.path.join(BASE_DIR, '/media/data_json/')
MEDID_URL = '/media/data_json/'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
# os.path.join(BASE_DIR, "static")
os.path.join(BASE_DIR, "fronted/dist/static")
]
STATIC_ROOT = os.path.join(BASE_DIR, "static/") # 部署专用 python3 manage.py collectstatic
主路由:
from django.urls import re_path, include
from django.views.generic import TemplateView
from django.views.static import serve
from dataAnalysis.settings import STATIC_ROOT
urlpatterns = [
# path('admin/', admin.site.urls),
re_path(r'^static/(?P<path>.*)/$', serve, {'document_root': STATIC_ROOT}),
re_path(r"dataAnalysis/", include(("dataAnalysisApp.urls", "dataAnalysisApp"), namespace="app")),
re_path(r'^$', TemplateView.as_view(template_name="index.html")),
]
子路由、views、处理数据的文件(科学计算)省略
第二步:服务器
首先这个服务器是个裸服务器,Linux也是个裸系统,意思就是刚买来的,还新鲜的!
第一步:使用Xftp/Xshell连接服务器,具体连接方法自行问度娘。
第二步:开启需要的端口,因为阿里云可以可视化快关端口,但是是linode不支持可视化,所以只能用命令来了。
# 查看版本
firewall-cmd --version
# 查看所有打开的端口
firewall-cmd --zone=public --list-ports
# 添加
# (--permanent永久生效,没有此参数重启后失效)该调参侠出手了!
firewall-cmd --zone=public --add-port=80/tcp --permanent
# 重新载入
firewall-cmd --reload
# 查看
firewall-cmd --zone= public --query-port=80/tcp
# 删除
firewall-cmd --zone= public --remove-port=80/tcp --permanent
第三步:安装Nginx
yum check-update && yum update
更新yum
查看wget是否安装
rpm -qa|grep "wget"
rpm是一个软件包管理工具
如果没有反应,执行yum -y install wget
可以安装
在root目录下操作:cd ~
就到root目录下面了
01.下载nginx wget http://nginx.org/download/nginx-1.17.0.tar.gz
02.解压
03.cd到刚解压的文件下,安装依赖
yum -y install pcre-devel zlib-devel
04.配置
./configure --prefix=/usr/local/nginx
如果:./configure: error: C compiler cc is not found
安装依赖yum -y install gcc gcc-c++ autoconf automake make
重新配置
上面粘贴失败时https://www.cnblogs.com/jpfss/p/9694842.html复制里面和上面相同的命令,再重新执行配置命令
05.make & make install
06.启动nginx /usr/local/nginx/sbin/nginx
07.在谷歌浏览器输入服务器IP,可看见Welcome to nginx!如果没有出现,根据上面开启防火墙端口的命令,开启防火墙,直到看见Nginx的欢迎界面
第四步:安装Python3.7
01.下载Python文件
wget https://www.python.org/ftp/python/3.7.1/Python-3.7.4.tar.xz
02.解压 tar -zxvf Py+Tab自动补全文件名,回车开始解压
03.切换目录解压好的Python文件夹下面之后,安装依赖
yum -y install gcc-* openssl-* libffi-devel sqlite-devel
04.配置:解决SSL的问题
可以参考的文章地址:https://www.jianshu.com/p/3ec24f563b81
开始配置Python:
./configure --enable-optimizations --with-openssl=$HOME/openssl
如果你的Django文件中使用pandas库,就执行:
./configure --with-openssl=$HOME/openssl
否则pandas会报错找不到lzma模快,因为我这个项目使用了pandas,所以我执行
./configure --with-openssl=$HOME/openssl
这个配置命令,注意:没有指定路径,默认安装了Python
05.编译 make -j8
06.安装:make install
07.命令行输入python3验证是否安装成功,exit()
退出Python
08.升级pip pip3 install --upgrade pip
当这个命令不能使用时:就是SSL没有安装好,可以使用:
pip3 install --upgrade pip -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
当然:这样可以安装,但是后面所有的库都需要这样安装,所以还是回过头来重新返回到上面的04步,再执行05。06。07。08。。。等等
第五步:虚拟环境
01.在当前目录执行:pip3 install virtualenv
02.退回到root目录,新建一个虚拟环境
virtualenv -p python www # www为虚拟环境名称
ls命令可以查看当前目录下多了一个www的文件夹
03.立即生效虚拟环境
source www/bin/activate
04.在虚拟环境中安装Django,注意当前版本
pip3 install django==2.2.6
05.检测Django是否已经安装成功,注意:只能在虚拟环境使用Django,退出虚拟环境就会报错:找不到Django
import django
print(django.VERSION)
如果打印出Django版本号,那么恭喜,可以进入第六步的操作
第六步:新建Django项目(测试)
01.,在虚拟环境中,切换到root目录
02.执行django-admin.py startproject 项目名(最好和本地项目名一致)
03.查看新建的项目(裸项目)django-admin.py
04.修改settings配置(建议在Xftp操作)
ALLOWED_HOSTS = ['173.255.222.190', 'localhost', '0.0.0.0:8000', '127.0.0.1', 'www.cwwage.com'] # 如果域名已经解析了,就可以往这个里面写了,否则不能写
05.启动django项目:python3 manage.py runserver 0.0.0.0:8000
06.如果报错是关于:sqlite3
可以参考:https://cloud.tencent.com/developer/article/1439327
新版本:wget https://www.sqlite.org/2019/sqlite-autoconf-3300100.tar.gz
注意执行:
vi ~/.bashrc
把上面参考文章里面的:export LD_LIBRARY_PATH="/usr/local/lib"
粘贴在最后一行
再执行:source ~/.bashrc
07.在浏览器打开服务器IP:8000,如果打开Django欢迎界面,操作正常,如果打不开,那么可能是8000端口没有开启,可查看文章上面的端口操作命令
08.退出虚拟环境:deactivate
,注意回到root目录cd ~
09.由于项目已经部署完毕,我忽略了测试的其他操作
第七步:配置uwsgi
01.安装uwsgi:pip3 install uwsgi
02.手动新建配置文件:
madir /etc/uwsgi
vim /etc/uwsgi/uwsgi.ini
文件内容:
[uwsgi]
chdir = /usr/local/nginx/html/dataAnalysis
module = dataAnalysis.wsgi
hodule = /root/www
master = true
processes = 5
socket = 0.0.0.0:9090
vacuum = true
pidfile = /var/run/uwsgi9090.pid
daemonize = /var/log/uwsgi9090.log
pythonpath=/root/www/lib/python3.7/site-packages
03.启动uwsgi:uwsgi --ini /etc/uwsgi/uwsgi.ini
04.查看服务器的端口状态:netstat -ntpl
,如果出现127.0.0.1:9090正常
05.关闭uwsgi:cat /varrun/uwsgi9090.pid
,会出现一个端口号,执行:kill -9 端口号
就可以关闭uwsgi服务
06.由于uwsgi的启动不是很方便,所封装了一个uwsgi启动,关闭的方法
vim /etc/init.d/uwsgi # 在init.d用tab时可能无反应,因为它只是一个快捷方式,在Linux中称之为软连接
然后依次执行 i Esc : q!
四个步骤,最后回车
用Xftp找到uwsgi文件,在文件里面添加下面的程序:
#! /bin/sh
DESC="uwsgi daemon"
NAME=uwsgi
DAEMON=/usr/local/bin/uwsgi
CONFIGFILE=/etc/uwsgi/$NAME.ini
PIDFILE=/var/run/${NAME}9090.pid
SCRIPTNAME=/etc/init.d/$NAME
FIFOFILE=/tmp/uwsgififo
set -e
[ -x "$DAEMON" ] || exit 0
do_start() {
if [ ! -f $PIDFILE ];then
$DAEMON $CONFIGFILE || echo -n "uwsgi running"
else
echo "The PID is exit..."
fi
}
do_stop() {
if [ -f $PIDFILE ];then
$DAEMON --stop $PIDFILE || echo -n "uwsgi not running"
rm -f $PIDFILE
echo "$DAEMON STOPED."
else
echo "The $PIDFILE dosen't found"
fi
}
do_reload() {
if [ -p $PIDFILE ];then
echo w > $FIFOFILE
else
$DAEMON --touch--workers--reload $PIDFILE || echo -n "uwsgi can't reload"
fi
}
do_status() {
ps aux|grep $DAEMON
}
case "$1" in
status)
echo -en "Status $NAME: \n"
do_status
;;
start)
echo -en "Starting $NAME: \n"
do_start
;;
stop)
echo -en "Stopping $NAME: \n"
do_stop
;;
reload|graceful)
echo -en "Reloading $NAME: \n"
do_reload
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|reload}" >&2
exit 3
;;
esac
exit 0
07.修改uwsgi的权限:chmod 755 /etc/init.d/uwsgi
08.再次启动uwsgi的操作:
/etc/init.d/uwsgi start # 启动
/etc/init.d/uwsgi stop # 关闭
/etc/init.d/uwsgi status # 查看运行状态
注意:这里不能随便开启或关闭,否则可能会报错:
signal_pidfile()/kill(): No such process [core/uwsgi.c line 1693]
一但报错:就得把刚才的uwsgi.ini和uwsgi删除重新执行启动和关闭,然系统找不到文件,然后再把删除的两个文件放在原来的位置,在启动uwsgi就没什么问题了,不过要注意提前备份。
09.查看uwsgi文件的位置:which uwsgi
第八步:配置nginx
就怕蒙圈,一股脑全粘贴到这里了
路径为:vim /usr/local/nginx/conf/nginx.conf
,可以到Xftp里面操作
user root;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
# 这个是nginx直接监听80端口,直接在服务器上找静态文件
server {
listen 80;
server_name www.cwwage.com;
location / {
root /usr/local/nginx/html/dataAnalysis/fronted/dist;
index index.html;
try_files $uri $uri/ /index.html;
}
}
# 这个是通过django查看静态文件,这个速度明显要慢,不过为了应对不同的情况,我下面也同样加载了静态文件
# 路径什么的,根据自己的需求,差不多只修改项目名就行了(dataAnalysis)
server {
listen 8000;
server_name www.cwwage.com cwwage.com;
charset utf-8;
# gzip_types application/json;
# 下面这个就是查看静态文件,是从django启动的,速度要慢一些
location /static{
alias /usr/local/nginx/html/dataAnalysis/static/;
}
location / { # 下面的配置有的注释了,可以随时打开就行了
include uwsgi_params;
uwsgi_pass 173.255.222.190:9090;
uwsgi_param UWSGI_SCRIPT dataAnalysis.wsgi;
uwsgi_param UWSGI_CHDIR /usr/local/nginx/html/dataAnalysis;
index index.html index.htm;
client_max_body_size 35m;
#uwsgi_cache_valid 1m;
#uwsgi_temp_file_write_size 64k;
#uwsgi_busy_buffers_size 64k;
#uwsgi_buffers 8 64k;
#uwsgi_buffer_size 64k;
uwsgi_read_timeout 300;
uwsgi_send_timeout 300;
uwsgi_connect_timeout 300;
}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
第九步:项目上线
01.用Xftp把项目放在/usr/local/nginx/html/
下面就可以了
02.在root目录下启动虚拟环境:source www/bin/activate
03.cd到项目目录里面,注意是有manage.py
的这一层目录。
启动项目,安装需要的库:python3 manage.py runserver 0.0.0.0:8000
,如果缺少哪个库,CTRL+C
退出django运行状态,执行pip3 install 库名
,然后再执行启动项目,如此反复,直到项目正常启动,其实是有快速导入库的方法,要在本地执行pip freeze > requirements.txt
生成一个requirements.txt
文件,在Linux中虚拟环境中pip install -r requirements.txt
可快速安装项目需要的库