Centos7搭建Django博客
技术积累 Python Centos7 django

DjangoBlog项目 Github 详情 部署教程 我搭建好的演示地址
我这里记录下我参考作者的文章部署的过程,mysql和python3和nginx环境已经ok的

环境准备:
1、Centos7
2、Mysql5.7
3、Python3.8
4、Nginx1.18
5、python虚拟环境目录 /python/env
6、DjangoBlog源码目录 /python/DjangoBlog

部署开始

#安装memcached和supervisor
yum install memcached supervisor -y

#动态链接库文件,添加python3和mysql的,我这里是源码安装的所以这里要加上,不然系统找不到
vim /etc/ld.so.conf
include ld.so.conf.d/*.conf
/usr/python3/lib
/data/mysql/lib

#设置python虚拟环境
pip3 install virtualenv
mkdir -p  /python/env && cd /python/env

[root@localhost env]# virtualenv -p /usr/python3/bin/python3  djangoblog
created virtual environment CPython3.8.2.final.0-64 in 356ms
  creator CPython3Posix(dest=/python/env/djangoblog, clear=False, global=False)
  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=/root/.local/share/virtualenv/seed-app-data/v1.0.1)
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

#进入python3虚拟环境
[root@localhost env]# source djangoblog/bin/activate
(djangoblog) [root@localhost env]# 

#安装djangoblog运行所需要的依赖
(djangoblog) [root@localhost env]# cd /python/DjangoBlog/
(djangoblog) [root@localhost DjangoBlog]# pip3 install -Ur requirements.txt
#这里遇到2个错误因为版本问题,修改下requirements.txt,文件中对应的修改成下面的然后再次执行
django-mdeditor==0.1.17.1
wrapt==1.11.0

mysql数据库配置

#创建数据库和授权
CREATE USER 'djangoblog'@'localhost' IDENTIFIED BY '123456';
CREATE DATABASE `djangoblog` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */;
GRANT all ON djangoblog.* TO 'djangoblog'@'localhost';
FLUSH PRIVILEGES;

#修改djangoblog配置文件
(djangoblog) [root@localhost DjangoBlog]# vim DjangoBlog/settings.py
#这里我用mysql.sock连接,用localhost有问题,之前我部署的用localhost没问题
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'djangoblog',
        'USER': 'djangoblog',
        'PASSWORD': '123456',
        'HOST': '/data/mysql/mysql.sock',
        'PORT': 3306,
        'OPTIONS': {'charset': 'utf8mb4'},
    }
}

#执行数据库迁移
(djangoblog) [root@localhost DjangoBlog]# ./manage.py makemigrations
Migrations for 'owntracks':
  owntracks/migrations/0001_initial.py
    - Create model OwnTrackLog
Migrations for 'servermanager':
  servermanager/migrations/0001_initial.py
    - Create model commands
    - Create model EmailSendLog
Migrations for 'accounts':
  accounts/migrations/0001_initial.py
    - Create model BlogUser
Migrations for 'blog':
  blog/migrations/0001_initial.py
    - Create model BlogSettings
    - Create model Links
    - Create model SideBar
    - Create model Tag
    - Create model Category
    - Create model Article
Migrations for 'comments':
  comments/migrations/0001_initial.py
    - Create model Comment
Migrations for 'oauth':
  oauth/migrations/0001_initial.py
    - Create model OAuthConfig
    - Create model OAuthUser
(djangoblog) [root@localhost DjangoBlog]# ./manage.py migrate
Operations to perform:
  Apply all migrations: accounts, admin, auth, blog, comments, contenttypes, oauth, owntracks, servermanager, sessions, sites
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying accounts.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying blog.0001_initial... OK
  Applying comments.0001_initial... OK
  Applying oauth.0001_initial... OK
  Applying owntracks.0001_initial... OK
  Applying servermanager.0001_initial... OK
  Applying sessions.0001_initial... OK
  Applying sites.0001_initial... OK
  Applying sites.0002_alter_domain_unique... OK
(djangoblog) [root@localhost DjangoBlog]# ./manage.py createsuperuser
用户名: admin
电子邮件地址: admin@admin.com
Password: 
Password (again): 
[2020-05-03 23:51:12,686] INFO [DjangoBlog.utils.news:63 utils] cache_decorator set cache:get_current_site key:4727341a8b52dd69399fc48a8a529c59
[2020-05-03 23:51:12,822] INFO [DjangoBlog.spider_notify.baidu_notify:30 spider_notify] {"remain":100000,"success":0,"not_same_site":["https://example.com/author/admin.html"]}
Superuser created successfully.
(djangoblog) [root@localhost DjangoBlog]# ./manage.py collectstatic --no-input

746 static files copied to '/python/env/DjangoBlog/collectedstatic'.
(djangoblog) [root@localhost DjangoBlog]# ./manage.py compress --force
Compressing... done
Compressed 4 block(s) from 26 template(s) for 0 context(s).

#启动测试,出现访问地址说明就ok的
(djangoblog) [root@localhost DjangoBlog]# ./manage.py runserver
Watching for file changes with StatReloader
[2020-05-03 23:52:04,067] INFO [django.utils.autoreload.run_with_reloader:598 autoreload] Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
May 03, 2020 - 23:52:04
Django version 3.0.3, using settings 'DjangoBlog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

gunicorn 配置

#安装gunicorn
(djangoblog) [root@localhost DjangoBlog]# pip3 install gunicorn
(djangoblog) [root@localhost DjangoBlog]# vim /python/gunicorn_start.sh
#!/bin/bash

NAME="DjangoBlog"
DJANGODIR=/python/DjangoBlog #Django project directory
USER=server # the user to run as
GROUP=server # the group to run as
NUM_WORKERS=1 # how many worker processes should Gunicorn spawn
DJANGO_SETTINGS_MODULE=DjangoBlog.settings # which settings file should Django use
DJANGO_WSGI_MODULE=DjangoBlog.wsgi # WSGI module name

echo "Starting $NAME as `whoami`"

# Activate the virtual environment
cd $DJANGODIR
source /python/env/djangoblog/bin/activate
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH

# Create the run directory if it doesn't exist
RUNDIR=$(dirname $SOCKFILE)
test -d $RUNDIR || mkdir -p $RUNDIR

# Start your Django Unicorn
# Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon)
exec /python/env/djangoblog/bin/gunicorn  ${DJANGO_WSGI_MODULE}:application \
--name $NAME \
--workers $NUM_WORKERS \
--user=$USER --group=$GROUP \
--log-level=debug \
--log-file=-

(djangoblog) [root@localhost DjangoBlog]# chmod +x /python/gunicorn_start.sh
(djangoblog) [root@localhost DjangoBlog]# cd /python
(djangoblog) [root@localhost python]# ./gunicorn_start.sh 
Starting DjangoBlog as root
dirname: missing operand
Try 'dirname --help' for more information.
[2020-05-03 23:59:35 +0800] [69002] [DEBUG] Current configuration:
  config: None
  bind: ['127.0.0.1:8000']
  backlog: 2048
  workers: 1
  worker_class: sync
  threads: 1
  worker_connections: 1000
  max_requests: 0
  max_requests_jitter: 0
  timeout: 30
  graceful_timeout: 30
  keepalive: 2
  limit_request_line: 4094
  limit_request_fields: 100
  limit_request_field_size: 8190
  reload: False
  reload_engine: auto
  reload_extra_files: []
  spew: False
  check_config: False
  preload_app: False
  sendfile: None
  reuse_port: False
  chdir: /python/DjangoBlog
  daemon: False
  raw_env: []
  pidfile: None
  worker_tmp_dir: None
  user: 0
  group: 0
  umask: 0
  initgroups: False
  tmp_upload_dir: None
  secure_scheme_headers: {'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'}
  forwarded_allow_ips: ['127.0.0.1']
  accesslog: None
  disable_redirect_access_to_syslog: False
  access_log_format: %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"
  errorlog: -
  loglevel: debug
  capture_output: False
  logger_class: gunicorn.glogging.Logger
  logconfig: None
  logconfig_dict: {}
  syslog_addr: udp://localhost:514
  syslog: False
  syslog_prefix: None
  syslog_facility: user
  enable_stdio_inheritance: False
  statsd_host: None
  dogstatsd_tags: 
  statsd_prefix: 
  proc_name: DjangoBlog
  default_proc_name: DjangoBlog.wsgi:application
  pythonpath: None
  paste: None
  on_starting: <function OnStarting.on_starting at 0x7fb564ee1b80>
  on_reload: <function OnReload.on_reload at 0x7fb564ee1ca0>
  when_ready: <function WhenReady.when_ready at 0x7fb564ee1dc0>
  pre_fork: <function Prefork.pre_fork at 0x7fb564ee1ee0>
  post_fork: <function Postfork.post_fork at 0x7fb564ef2040>
  post_worker_init: <function PostWorkerInit.post_worker_init at 0x7fb564ef2160>
  worker_int: <function WorkerInt.worker_int at 0x7fb564ef2280>
  worker_abort: <function WorkerAbort.worker_abort at 0x7fb564ef23a0>
  pre_exec: <function PreExec.pre_exec at 0x7fb564ef24c0>
  pre_request: <function PreRequest.pre_request at 0x7fb564ef25e0>
  post_request: <function PostRequest.post_request at 0x7fb564ef2670>
  child_exit: <function ChildExit.child_exit at 0x7fb564ef2790>
  worker_exit: <function WorkerExit.worker_exit at 0x7fb564ef28b0>
  nworkers_changed: <function NumWorkersChanged.nworkers_changed at 0x7fb564ef29d0>
  on_exit: <function OnExit.on_exit at 0x7fb564ef2af0>
  proxy_protocol: False
  proxy_allow_ips: ['127.0.0.1']
  keyfile: None
  certfile: None
  ssl_version: 2
  cert_reqs: 0
  ca_certs: None
  suppress_ragged_eofs: True
  do_handshake_on_connect: False
  ciphers: None
  raw_paste_global_conf: []
  strip_header_spaces: False
[2020-05-03 23:59:35 +0800] [69002] [INFO] Starting gunicorn 20.0.4
[2020-05-03 23:59:35 +0800] [69002] [DEBUG] Arbiter booted
[2020-05-03 23:59:35 +0800] [69002] [INFO] Listening at: http://127.0.0.1:8000 (69002)
[2020-05-03 23:59:35 +0800] [69002] [INFO] Using worker: sync
[2020-05-03 23:59:35 +0800] [69002] [DEBUG] 1 workers
[2020-05-03 23:59:35 +0800] [69008] [INFO] Booting worker with pid: 69008

Nginx 配置

#修改nginx配置文件 nginx.conf
server {

    listen 80;
    server_name www.djangoblog.com;
    root /python/DjangoBlog/;

    access_log logs/django_access.log;
    error_log logs/django_error.log;

    location /static/ {
        alias /python//DjangoBlog/collectedstatic/;
        expires max;
        access_log        off;
        log_not_found     off;
    }
    location /media {
        # 静态文件配置
        alias /python/DjangoBlog/uploads/;
        expires max;
    }
    location ~ \.py$ {
        return 403;
    }

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_redirect off;
        if (!-f $request_filename) {
            proxy_pass http://127.0.0.1:8000;
            break;
        }
    }

}

#重启nginx
nginx -s reload

Supervisor 配置

(djangoblog) [root@localhost ~]# vim /etc/supervisord.d/djangoblog.ini

[program:djangoblog]
command = /python/gunicorn_start.sh
user = root
autostart=true
autorestart=true
redirect_stderr = true
stdout_logfile = /var/log/djangoblog.log
stderr_logfile=/var/log/djangoblog.err

(djangoblog) [root@localhost ~]# supervisord -c /etc/supervisord.conf 
(djangoblog) [root@localhost ~]# supervisorctl update
(djangoblog) [root@localhost ~]# supervisorctl reload
Restarted supervisord
(djangoblog) [root@localhost ~]# systemctl start memcached

访问站点

Centos7搭建Django博客

Centos7搭建Django博客


本文最后记录时间 2024-03-30
文章链接地址:
https://wojc.cn/archives/550.html
本站文章除注明[转载|引用|来源],均为本站原创内容,转载前请注明出处
使用腾讯云CDN的SDK 用脚本去刷新URL缓存
yum安装出现error: %pre() scriptlet failed, exit status 1, Error in PREIN scriptlet in rpm package 错误
在Nginx中配置使用Geoip2模块
pip 安装错误 Command "python setup.py egg_info" failed with error code

Centos7 搭建OpenVPN 基于证书认证

Linux下Python3.x版本安装

留言

顶部