上回说到,我们给前端界面添加了样式,这回我就不配置其他数据库了,就用默认的 SQLite,直接进行部署,在部署之前,我们现在服务器上安装相应的运行环境,我在这里使用 Gunicorn Nginx,进行部署,我们先来简单配置运行环境。
Python 安装以及创建虚拟环境
因为这个项目是一个 Python Web 项目,所以我们首先需要在服务器安装 Python,我就直接通过源码安装 Python,首先是下载源码压缩包,进行解压,进入源码目录,以 root 身份执行命令:
wget https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tgztar xf Python-3.7.6.tgzcd Python-3.7.6/
然后执行以 root 身份执行命令:
./configuremakemake install
如果没有报错意味着安装完成,接下来我们就只要用普通用户来运行项目了,在此之前我们首先需要安装虚拟环境包,以 root 身份执行命令:
pip3 install virtualenv
安装完成之后就以普通用户的身份创建一个虚拟环境,执行命令:
python3 -m virtualenv personal_website_env
接着就是进入其中并激活环境,执行命令:
cd personal_website_envsource bin/activate
然后就是安装 Django、Gunicorn 和 django-ckeditor-5,其中 django-ckeditor-5 安装起来有些麻烦,我们稍后再说,先安装 Django 和 Gunicorn,直接执行命令。
pip3 install Djangopip3 install gunicorn
如果都没有报错就意味着安装成功,接下来就是讲一下安装 django-ckeditor-5,这个我们直接把修改的源码先上传到服务器。然后进入源码目录并安装。
cd ../django-ckeditor-5-master/python3 setup.py install
运行项目
该安装的都装好了,接下来把项目上传到服务器,并启动项目:
python manage.py runserver
运行之后发现报错,如图所示。
我们需要去升级 SQLite 版本,当然也可以给 Django 降级,也可以配置其他数据库,我选择升级 SQLite,以 root 身份执行下面的命令:
wget https://www.sqlite.org/2020/sqlite-autoconf-3320100.tar.gztar xf sqlite-autoconf-3320100.tar.gzcd sqlite-autoconf-332010./configuremake && make installmv /usr/bin/sqlite3 /usr/bin/sqlite3_oldln -s /usr/local/bin/sqlite3 /usr/bin/sqlite# 设置开机自启动执行,可以将下面的export语句写入 ~/.bashrc 文件中,如果如果你想立即生效,可以执行source 〜/.bashrc 将在每次启动终端时执行export LD_LIBRARY_PATH="/usr/local/lib"
如果没有报错就是升级成功,重新连接远程服务器,以普通用户身份进入虚拟环境运行项目,如图所示。
发现还是报错,这是因为我们没有安装对应的库,用 pip3 安装一下 pillow 库即可。
再次运行发现没有报错,我们这次关闭防火墙,让这次运行可以被我们在本地访问,先用 root 身份关闭防火墙,命令如下:
systemctl stop firewalld.servicesystemctl disable firewalld.service
然后运行项目,因为这次要求远程访问,所以和之前的有些不一样,命令如下:
python manage.py runserver 0.0.0.0:8000
来看一下远程访问的效果,如图所示。
看样子应该没啥问题了,接下来就是配置生产环境,首先把 DEBUG 改成 False,然后定义 STATIC_ROOT;ALLOWED_HOSTS 我之前改过了,直接添加一个 '*' 到这个列表中。
配置生产环境
配置生产环境主要是配置生产环境的设置,也就是 settings.py,直接给出配置后的代码。
"""Django settings for PersonalWebsite project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, seehttps://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, seehttps://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = 'x-eg)ze7__0j(g8$gp#$_b(l=i39n k-*%xdteius0k&3-h=^1'
# SECURITY WARNING: don't run with debug turned on in production!DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definitionMEDIA_URL = '/media/'MEDIA_ROOT = os.path.join(BASE_DIR, 'media')customColorPalette = [ { 'color': 'hsl(4, 90%, 58%)', 'label': 'Red' }, { 'color': 'hsl(340, 82%, 52%)', 'label': 'Pink' }, { 'color': 'hsl(291, 64%, 42%)', 'label': 'Purple' }, { 'color': 'hsl(262, 52%, 47%)', 'label': 'Deep Purple' }, { 'color': 'hsl(231, 48%, 48%)', 'label': 'Indigo' }, { 'color': 'hsl(207, 90%, 54%)', 'label': 'Blue' }, ]CKEDITOR_5_CONFIGS = { 'default': { 'blockToolbar': [ 'paragraph', 'heading1', 'heading2', 'heading3', '|', 'bulletedList', 'numberedList', '|', 'blockQuote', 'imageUpload' ], 'toolbar': ['heading', '|', 'outdent', 'indent', '|', 'bold', 'italic', 'link', 'underline', 'strikethrough', 'code', 'subscript', 'superscript', 'highlight', '|', 'alignment', 'codeBlock', 'bulletedList', 'numberedList', 'todoList', '|', 'blockQuote', 'imageUpload', '|', 'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat', 'insertTable'], 'image': { 'toolbar': ['imageTextAlternative', 'imageTitle', '|', 'imageStyle:alignLeft', 'imageStyle:full', 'imageStyle:alignRight', 'imageStyle:alignCenter', 'imageStyle:side', '|'], 'styles': [ 'full', 'side', 'alignLeft', 'alignRight', 'alignCenter', ] }, 'table': { 'contentToolbar': ['tableColumn', 'tableRow', 'mergeTableCells', 'tableProperties', 'tableCellProperties'], 'tableProperties': { 'borderColors': customColorPalette, 'backgroundColors': customColorPalette }, 'tableCellProperties': { 'borderColors': customColorPalette, 'backgroundColors': customColorPalette } }, 'heading': { 'options': [ {'model': 'paragraph', 'title': 'Paragraph', 'class': 'ck-heading_paragraph'}, {'model': 'heading1', 'view': 'h1', 'title': 'Heading 1', 'class': 'ck-heading_heading1'}, {'model': 'heading2', 'view': 'h2', 'title': 'Heading 2', 'class': 'ck-heading_heading2'}, {'model': 'heading3', 'view': 'h3', 'title': 'Heading 3', 'class': 'ck-heading_heading3'} ] } }}
INSTALLED_APPS = [ 'personal_website.apps.PersonalWebsiteConfig',
'django_ckeditor_5',
'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',]
MIDDLEWARE = [ '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',]
ROOT_URLCONF = 'PersonalWebsite.urls'
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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 = 'PersonalWebsite.wsgi.application'
# Database# https://docs.djangoproject.com/en/3.0/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/3.0/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', },]
# Internationalization# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'if DEBUG: STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ]else: STATIC_ROOT = os.path.join(BASE_DIR, "static")
接下来收集静态文件,运行命令:
python manage.py collectstatic
然后运行看看,发现样式并没有加载,如图所示。
这是因为一旦把 DEBUG 设置成了 False,Django 它就不会直接寻找静态文件,我们需要借助 Nginx 来实现静态文件的寻找,在此之前我们先让 gunicorn 以守护态运行这个项目,这里我就不开放远程访问了,直接让 gunicorn 容器在本地运行,远程的事情就交给 Nginx 来做,命令如下:
gunicorn -b 127.0.0.1:8000 --daemon PersonalWebsite.wsgi:application
接下来安装 nginx,用 root 身份运行命令:
sudo yum install yum-utilsvim /etc/yum.repos.d/nginx.repo
写入内容如下:
[nginx-stable]name=nginx stable repobaseurl=http://nginx.org/packages/centos/$releasever/$basearch/gpgcheck=1enabled=1gpgkey=https://nginx.org/keys/nginx_signing.keymodule_hotfixes=true
[nginx-mainline]name=nginx mainline repobaseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/gpgcheck=1enabled=0gpgkey=https://nginx.org/keys/nginx_signing.keymodule_hotfixes=true
然后安装并寻找配置文件,命令如下:
sudo yum install nginxnginx -t
找到配置文件之后就可以进行修改了,这里主要修改两个配置文件,分别是:
/etc/nginx/nginx.conf
/etc/nginx/conf.d/personal_website.conf
如果没有就进行创建对应的文件,这里直接给出修改后的内容,首先是 /etc/nginx/nginx.conf,这个文件改动的不是很多,修改后的内容如下:
user root;worker_processes 1;
error_log /var/log/nginx/error.log warn;pid /var/run/nginx.pid;
events { worker_connections 1024;}
http { include /etc/nginx/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 /var/log/nginx/access.log main;
sendfile on; #tcp_nopush on;
keepalive_timeout 65;
#gzip on;
#include /etc/nginx/conf.d/*.conf; include /etc/nginx/conf.d/personal_website.conf;}
最后是/etc/nginx/conf.d/personal_website.conf,内容如下:
server { listen 80; server_name localhost;
#charset koi8-r; #access_log /var/log/nginx/host.access.log main;
location / { proxy_pass http://127.0.0.1:8000; } location /static { alias /home/chenzhihao/personal_website_env/PersonalWebsite/static; } location /media { alias /home/chenzhihao/personal_website_env/PersonalWebsite/media; }
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; }
# proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ .php$ { # proxy_pass http://127.0.0.1; #}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ .php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #}
# deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /.ht { # deny all; #}}
目前已经全部完成了,我们最后看一下效果,如图所示。