首页 > 其他分享 >基于 Django 的个人网站(6)

基于 Django 的个人网站(6)

时间:2022-12-01 11:07:05浏览次数:45  
标签:基于 网站 os django nginx conf contrib Django root



上回说到,我们给前端界面添加了样式,这回我就不配置其他数据库了,就用默认的 SQLite,直接进行部署,在部署之前,我们现在服务器上安装相应的运行环境,我在这里使用 Gunicorn+Nginx,进行部署,我们先来简单配置运行环境。




Python 安装以及创建虚拟环境


因为这个项目是一个 Python Web 项目,所以我们首先需要在服务器安装 Python,我就直接通过源码安装 Python,首先是下载源码压缩包,进行解压,进入源码目录,以 root 身份执行命令:

wget https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tgz
tar xf Python-3.7.6.tgz
cd Python-3.7.6/

然后执行以 root 身份执行命令:

./configure
make
make install

如果没有报错意味着安装完成,接下来我们就只要用普通用户来运行项目了,在此之前我们首先需要安装虚拟环境包,以 root 身份执行命令:

pip3 install virtualenv

安装完成之后就以普通用户的身份创建一个虚拟环境,执行命令:

python3 -m virtualenv personal_website_env

接着就是进入其中并激活环境,执行命令:

cd personal_website_env
source bin/activate

然后就是安装 Django、Gunicorn 和 django-ckeditor-5,其中 django-ckeditor-5 安装起来有些麻烦,我们稍后再说,先安装 Django 和 Gunicorn,直接执行命令。

pip3 install Django
pip3 install gunicorn

如果都没有报错就意味着安装成功,接下来就是讲一下安装 django-ckeditor-5,这个我们直接把修改的源码先上传到服务器。然后进入源码目录并安装。

cd ../django-ckeditor-5-master/
python3 setup.py install



运行项目


该安装的都装好了,接下来把项目上传到服务器,并启动项目:

python manage.py runserver

运行之后发现报错,如图所示。

基于 Django 的个人网站(6)_python

我们需要去升级 SQLite 版本,当然也可以给 Django 降级,也可以配置其他数据库,我选择升级 SQLite,以 root 身份执行下面的命令:

wget https://www.sqlite.org/2020/sqlite-autoconf-3320100.tar.gz
tar xf sqlite-autoconf-3320100.tar.gz
cd sqlite-autoconf-332010
./configure
make && make install
mv /usr/bin/sqlite3 /usr/bin/sqlite3_old
ln -s /usr/local/bin/sqlite3 /usr/bin/sqlite
# 设置开机自启动执行,可以将下面的export语句写入 ~/.bashrc 文件中,如果如果你想立即生效,可以执行source 〜/.bashrc 将在每次启动终端时执行
export LD_LIBRARY_PATH="/usr/local/lib"

如果没有报错就是升级成功,重新连接远程服务器,以普通用户身份进入虚拟环境运行项目,如图所示。

基于 Django 的个人网站(6)_nginx_02

发现还是报错,这是因为我们没有安装对应的库,用 pip3 安装一下 pillow 库即可。

基于 Django 的个人网站(6)_nginx_03

再次运行发现没有报错,我们这次关闭防火墙,让这次运行可以被我们在本地访问,先用 root 身份关闭防火墙,命令如下:

systemctl stop firewalld.service
systemctl disable firewalld.service

然后运行项目,因为这次要求远程访问,所以和之前的有些不一样,命令如下:

python manage.py runserver 0.0.0.0:8000

来看一下远程访问的效果,如图所示。

基于 Django 的个人网站(6)_python_04

看样子应该没啥问题了,接下来就是配置生产环境,首先把 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, see
https://docs.djangoproject.com/en/3.0/topics/settings/


For the full list of settings and their values, see
https://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 definition
MEDIA_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

然后运行看看,发现样式并没有加载,如图所示。

基于 Django 的个人网站(6)_python_05

这是因为一旦把 DEBUG 设置成了 False,Django 它就不会直接寻找静态文件,我们需要借助 Nginx 来实现静态文件的寻找,在此之前我们先让 gunicorn 以守护态运行这个项目,这里我就不开放远程访问了,直接让 gunicorn 容器在本地运行,远程的事情就交给 Nginx 来做,命令如下:

gunicorn -b 127.0.0.1:8000 --daemon PersonalWebsite.wsgi:application

接下来安装 nginx,用 root 身份运行命令:

sudo yum install yum-utils
vim /etc/yum.repos.d/nginx.repo

写入内容如下:

[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true


[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

然后安装并寻找配置文件,命令如下:

sudo yum install nginx
nginx -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;
#}
}

目前已经全部完成了,我们最后看一下效果,如图所示。

基于 Django 的个人网站(6)_nginx_06

显示的和之前一样没有什么问题,点进富文本文章标题会发现内容包括图片在内都是正常的。网站终于弄完了,以后公众号文章或者其他技术文章都会同步到我的网站,我暂时先输出一些内容,等到内容有些多了我再把网站域名发给大家。

今天的文章有不懂的可以后台回复“加群”,备注:小陈学Python,不备注可是会被拒绝的哦~!



基于 Django 的个人网站(6)_nginx_07


标签:基于,网站,os,django,nginx,conf,contrib,Django,root
From: https://blog.51cto.com/u_15829940/5901364

相关文章

  • python3 venv虚拟环境创建与安装Django
    创建虚拟环境C:\Users\Xiao>python-mvenvD:\Pythonwork\venvtest​​激活虚拟环境C:\Users\Xiao>D:\Pythonwork\venvtest\Scripts\activate(venvtest)C:\Users\Xiao>​......
  • 房山昌平游戏网站高防BGP物理机
    空间不够大,可以选择塔式服务器。由于服务器的主板扩展性较强、插槽也多出一堆,所以个头比普通主板大一些,因此塔式服务器的主机机箱也比标准的ATX机箱要大,一般都会预留足够的......
  • 房山昌平网站BGP物理机租用
    重要性仅次于防护能力。虽然有足够的防护能力应对任何规模的DDoS攻击,但如果线路质量差的话,势必影响防护的响应处理速度与稳定性,从而损害用户访问网站或APP的体验。特别是生......
  • 房山昌平高防网站BGP物理机
    您租用时选择了一个防御值的话,那么你的服务器即使遭受了攻击,只要在这个防御值范围内是不可能被打死的,而且现在很多高防机房也升级了云堤清洗功能,在量开始的时候就开始清洗......
  • 基于云开发的答题活动小程序v2.0-首页设计与实现
    项目技术栈微信原生小程序+云开发。为什么选择微信原生小程序进行开发呢?因为能够直接应用它的云开发能力吖。我这里主要使用了云开发能力中的小程序端SDK,说白了就是在jav......
  • 用DevExpress实现基于HTML&CSS的桌面应用程序的UI(二)
    DevExpressWinForm拥有180+组件和UI库,能为WindowsForms平台创建具有影响力的业务解决方案。DevExpressWinForm能完美构建流畅、美观且易于使用的应用程序,无论是Office风......
  • 让网站首页变灰代码
    不少网站首页已经变成了灰色。下面笔者整理了几种让网页变灰色的CSS代码,供各位站长参考!方法1:支持IE<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"......
  • 一行css网站变灰色?
    上代码:-webkit-filter:grayscale(100%);-moz-filter:grayscale(100%);-o-filter:grayscale(100%);filter:grayscale(100%);filter:progid:DXImageTransform.Mic......
  • IIS 网站搭建,内部可以访问,外部不能访问
    文章来源:https://blog.csdn.net/pigeon79/article/details/123616787今天配置好IIS环境的时候发现外网不能访问了,内网可以访问,检查了绑定、权限等等都没问题,到底是哪里出......
  • 干货 | 博云基于OVS自研容器网络插件在金融企业的落地实践
     过去几年博云在企业中落地容器云平台遇到了很多痛点,其中一个比较典型的痛点来自网络方面,今天很高兴跟大家聊聊这个话题并介绍下我们基于OVS自研的CNI插件——内部称之为fa......