Linux下配置Django_Apache_Mysql环境(CentOS 7.5)

Posted samtech

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux下配置Django_Apache_Mysql环境(CentOS 7.5)相关的知识,希望对你有一定的参考价值。

 

本文将介绍如何在Linux上部署Django + mysql + Apache环境。我们知道,Django内置的http服务器只能工作在单线程下,做开发和调试时候是可以的,但是生产环境通常都会有多用户并发,而且django的simple HTTP server处理大量静态文件的性能太差,所以要用apache做前端。Django自带的SQLite数据库权限只依赖于文件系统,没有用户帐户的概念,这里我们使用典型的关系型数据库Mysql。看似简单的环境搭建,在实际操作过程中还是遇到了不少的大坑,所以特地将过程记录下来,也希望对大家有小小的帮助。

CentOS 7.5  +  python 2.7.5  + Django 1.11.14  +  Apache 2.4.6  +  Mysql 5.7.23

 

1. 安装Django

Linux上我们可以直接使用pip安装Django

 

1.1  安装python(使用CentOS 7.5自带的python即可)

[[email protected] ~]# python --version
Python 2.7.5

 

1.2  网上下载get-pip.py文件安装pip:

wget https://bootstrap.pypa.io/get-pip.py

 

1.3  pip安装django

[[email protected] ~]# pip install django
[[email protected] ~]# python
Python 2.7.5 (default, Jul 13 2018, 13:06:57)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.get_version()
1.11.14

 

2. 安装Apache

Linux上使用yum安装Apache即可

[[email protected] ~]# yum install httpd
[[email protected] ~]# httpd -V
[Thu Aug 16 20:57:04.487586 2018] [so:warn] [pid 1605] AH01574: module wsgi_module is already loaded, skipping
Server version: Apache/2.4.6 (CentOS)
Server built:   Jun 27 2018 13:48:59
Servers Module Magic Number: 20120211:24
Server loaded:  APR 1.4.8, APR-UTIL 1.5.2
Compiled using: APR 1.4.8, APR-UTIL 1.5.2
Architecture:   64-bit
Server MPM:     prefork
  threaded:     no
    forked:     yes (variable process count)

注意:使用yum安装的httpd,其安装目录位于/etc/httpd/,我们只需要配置/etc/httpd/conf/httpd.conf即可

 

3. 安装Mysql

我们使用yum安装Mysql,需要先更新yum源

 

[root[email protected] ~]# wget http://dev.mysql.com/get/mysql57-community-release-el7-8.noarch.rpm
[[email protected] ~]# rpm -ivh mysql57-community-release-el7-8.noarch.rpm
[[email protected] ~]# yum install mysql-community-server

 

注意:yum安装的Mysql其文件目录如下

  • 配置文件:/etc/my.cnf
  • 日志文件:/var/log/var/log/mysqld.log
  • 服务启动脚本:/usr/lib/systemd/system/mysqld.service
  • socket文件:/var/run/mysqld/mysqld.pid

 

4. 配置(重点)

以上三步都非常容易,但是将这三个环境配置好,还是费了我不少的时间...

4.1  配置Mysql

 

[[email protected] ~]# systemctl start mysqld
# 开启Mysql服务后,会为root设置一个默认密码,我们首先重置密码
# 获得默认密码
[[email protected] ~]# cat /var/log/mysqld.log | grep -i password
[[email protected] ~]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 8
Server version: 5.7.23 MySQL Community Server (GPL)

mysql>ALTER USER root@localhost IDENTIFIED BY Sam_tech_0912;

# 重置密码后,我们创建一个数据库,因为后续django连接Mysql时需要输入数据库名称
mysql> create database Platform default charset=utf8;
Query OK, 1 row affected (0.00 sec)

mysql> quit
Bye

 

4.2  django中配置Mysql

 

django中关于Mysql的配置:

DATABASES = {
    default: {
        # ENGINE: django.db.backends.sqlite3,
        # NAME: os.path.join(BASE_DIR, db.sqlite3),
        ENGINE: django.db.backends.mysql,
        NAME: Platform,
        HOST: 127.0.0.1,
        PORT: 3306,
        USER: root,
        PASSWORD: Sam_tech_0912,
    }
}

 

django中其他的部分的配置:

DEBUG = True

ALLOWED_HOSTS = ["*",]

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,
            ],
        },
    },
]

LANGUAGE_CODE = zh-hans

TIME_ZONE = Asia/Shanghai

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = /static/
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

 

4.3  配置Apache

 

重点:安装mod_wsgi

[[email protected] ~]# yum install mod_wsgi
[[email protected] ~]# rpm -qa | grep wsgi
mod_wsgi-3.4-12.el7_0.x86_64

 

编辑配置文件 /etc/httpd/conf/httpd.conf

ServerRoot "/etc/httpd"

# 设定Apache监听的端口号,可以设定多个
Listen 80

# 重点:这句是加载刚刚安装的wsgi模块,有了它django才能部署到Apache上,切记!!!
LoadModule wsgi_module modules/mod_wsgi.so


Include conf.modules.d/*.conf

User apache
Group apache

ServerAdmin [email protected]

ServerName localhost:80

<Directory />
    AllowOverride none
    Require all denied
</Directory>

    DocumentRoot "/var/www/html"

<Directory "/var/www">
    AllowOverride None
    Require all granted
</Directory>

<Directory "/var/www/html">
    Options Indexes FollowSymLinks

    AllowOverride None

    Require all granted
</Directory>

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

<Files ".ht*">
    Require all denied
</Files>

ErrorLog "logs/error_log"

LogLevel warn

<IfModule log_config_module>
    LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" combined
    LogFormat "%h %l %u %t "%r" %>s %b" common

    <IfModule logio_module>
      LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i" %I %O" combinedio
    </IfModule>

    CustomLog "logs/access_log" combined
</IfModule>

<IfModule alias_module>

    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

</IfModule>

<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    TypesConfig /etc/mime.types

    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz



    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>

AddDefaultCharset UTF-8

<IfModule mime_magic_module>
    MIMEMagicFile conf/magic
</IfModule>


EnableSendfile on

IncludeOptional conf.d/*.conf

# 我们在/etc/httpd/conf/下新建httpd-vhosts.conf虚拟主机配置文件,完成对80端口的配置
# 这句是告诉Apache去调用httpd-vhosts.conf
# 虚拟主机中的配置参数将覆盖httpd.conf主配置文件中的设定
Include conf/httpd-vhosts.conf

 

虚拟主机配置文件(关键一步

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "/home/python_projects/Platform"
    ServerName samlinux01-platform.com
    ServerAlias sam-platform.com
    ErrorLog "logs/platform_error.log"
    CustomLog "logs/platform_access.log" common


    WSGIScriptAlias / "/home/python_projects/Platform/Platform/wsgi.py"
    # 一定要定义python-path到项目目录,否则会报出相关模块无法找到的错误,切记!!!
    WSGIDaemonProcess samlinux01-platform.com python-path=/home/python_projects/Platform
    WSGIProcessGroup samlinux01-platform.com
    WSGIScriptReloading On
    
    # 设定Apache访问django的项目目录

    Alias /static /home/python_projects/Platform/static
    Alias /media /home/python_projects/Platform/media

    <Directory /home/python_projects/Platform/media>
        AllowOverride None
        Options Indexes FollowSymLinks
        Require all granted
    </Directory>
    <Directory /home/python_projects/Platform/static>
        AllowOverride None
        Options Indexes FollowSymLinks
        Require all granted
    </Directory>
    <Directory /home/python_projects/Platform/Platform>
        <Files wsgi.py>
            AllowOverride None
            Require all granted
        </Files>
    </Directory>
</VirtualHost>

注意:每次编辑完成后都需要重启httpd服务使配置生效

[[email protected] ~]# httpd -t
[Thu Aug 16 20:35:06.439115 2018] [so:warn] [pid 1520] AH01574: module wsgi_module is already loaded, skipping
Syntax OK
[[email protected] ~]# systemctl restart httpd.service

 

编辑django中的 wsgi.py文件

"""
WSGI config for Platform project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Platform.settings")

application = get_wsgi_application()

# 添加项目路径到python的环境变量中
# For Apache server
import sys
project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_dir)

 

至此,大功告成,我们直接可以通过80端口访问我们的项目,虽然上面的步骤简单,但是网上查的资料并没有特别详细完整的,中间还是走了不少的弯路,所以特意将配置步骤记录下来,方便后续再次配置!

 

以上是关于Linux下配置Django_Apache_Mysql环境(CentOS 7.5)的主要内容,如果未能解决你的问题,请参考以下文章

怎么在linux下配置yum服务器?

java在linux环境下的配置

linux下修改完配置文件如何保存?

如何查看linux 下 nginx配置

记录下WIN下配置LINUX虚拟机及PYTHON环境

linux下yum安装及配置