Django 部署工作之数据库。

写在前面

操作系统:RHEL / Fedora / CentOS

安装 MariaDB 及其他组件

1
$ sudo yum install python-pip python-devel gcc mariadb-server mariadb-devel

若使用的是 Python3 环境, 则需要安装的是 python3-devel ,具体请参照这里

启动 MariaDB

1
2
$ sudo systemctl start mariadb
$ sudo systemctl enable mariadb   // 使 MariaDB 服务开机启动,开发环境不必须。

初始化 MariaDB

1
$ sudo mysql_secure_installation

数据库配置

登入 MariaDB 数据库:

1
$ mysql -uroot -p

新建数据库:

1
MariaDB [(none)]> create database django_project character set utf8;

配置数据库用户:

1
2
3
MariaDB [(none)]> create user 'django_project_user'@'localhost' identified by 'password';
MariaDB [(none)]> grant all privileges on django_project.* to 'django_project_user'@'localhost';
MariaDB [(none)]> flush privileges;

退出 MariaDB

1
MariaDB [(none)]> quit

安装 mysqlclient

1
$ pip install mysqlclient

请确保已安装所有的依赖。具体请见这里

配置 Django

settings.py 文件中更改数据库配置:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'DATABASE_NAME',
        'USER': 'DATABASE_USER',
        'PASSWORD': 'DATABASE_PASSWORD',
        'HOST': '',  # Default: localhost
        'PORT': '',  # Default: 3306,
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        },
    }
}

具体可查阅这里这里

迁移数据库

基本上就配置完成啦,重新迁移数据库看看是否正常:

1
2
$ ./manage.py makemigrations
$ ./manage.py migrate

迁移成功后就可以正常使用以及建立超级用户啦~


知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。