Django系列---使用MySql數據庫

Django默認使用的sqlite3,這在實際的生產環境中是不推薦的;

1. 創建數據庫

Linux VM_0_15_centos 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

1.1. 使用utf8mb4編碼

mysql的utf-8編碼最多隻支持3個字節,而移動端的一些表情都是以4個字節存儲的;utf8mb4是一個替代的方案,建議創建數據庫和表都以utf8mb4替代utf-8

1.1.1. 確定mysql的配置文件

# 系統中my.cnf文件的位置
[luizyao@VM_0_15_centos ~]$ locate my.cnf
/etc/my.cnf
/etc/my.cnf.d
/etc/my.cnf.d/client.cnf
/etc/my.cnf.d/mysql-clients.cnf
/etc/my.cnf.d/server.cnf

# mysql啓動時,讀取配置文件的目錄順序
[luizyao@VM_0_15_centos ~]$  mysql --help | head -n 7
mysql  Ver 15.1 Distrib 5.5.56-MariaDB, for Linux (x86_64) using readline 5.1
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Usage: mysql [OPTIONS] [database]

Default options are read from the following files in the given order:
/etc/mysql/my.cnf /etc/my.cnf ~/.my.cnf

1.1.2. 修改配置文件

/etc/my.cnf

[client] 
default-character-set = utf8mb4

[mysql] 
default-character-set = utf8mb4

[mysqld]
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd
character-set-client-handshake = FALSE 
character-set-server = utf8mb4 
collation-server = utf8mb4_unicode_ci 
init_connect='SET NAMES utf8mb4'

1.1.3. 重啓數據庫服務,檢查相關字段

# 保證character_set_client、character_set_connection、character_set_database、character_set_results和character_set_server的值一定是utf8mb4
MariaDB [(none)]> SHOW VARIABLES WHERE Variable_name LIKE 'character_set_%' OR Variable_name LIKE 'collation%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8mb4                    |
| character_set_connection | utf8mb4                    |
| character_set_database   | utf8mb4                    |
| character_set_filesystem | binary                     |
| character_set_results    | utf8mb4                    |
| character_set_server     | utf8mb4                    |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
| collation_connection     | utf8mb4_unicode_ci         |
| collation_database       | utf8mb4_unicode_ci         |
| collation_server         | utf8mb4_unicode_ci         |
+--------------------------+----------------------------+
11 rows in set (0.02 sec)

1.1.4. 新建數據庫

MariaDB [(none)]> create database blogproject;
Query OK, 1 row affected (0.01 sec)

--查看blogproject創建時候使用的編碼,回顯中註釋的部分可以看出,使用的是utf8mb4編碼
MariaDB [mysql]> show create database blogproject;
+-------------+----------------------------------------------------------------------------------------------------+
| Database    | Create Database                                                                                    |
+-------------+----------------------------------------------------------------------------------------------------+
| blogproject | CREATE DATABASE `blogproject` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */ |
+-------------+----------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

1.2. 使用已經存在的數據庫

1.2.1. 修改已有數據庫的編碼

MariaDB [(none)]> alter database blogproject character set utf8mb4;

1.3. 爲Django項目新建一個數據庫用戶

-- 賦予這個新用戶增刪改查等權限,不授予drop的權限;並且,只允許本地客戶端登陸;
MariaDB [mysql]> grant alter,create,delete,index,insert,select,update,trigger on blogproject.* to <用戶名>@localhost identified by '<密碼>'; 
Query OK, 0 rows affected (0.04 sec)

MariaDB [mysql]> flush privileges;
Query OK, 0 rows affected (0.03 sec)

-- 檢查權限,祕密默認是加密存儲
MariaDB [blogproject]> show grants for <用戶名>@localhost;
+----------------------------------------------------------------------------------------------------------------+
| Grants for <用戶名>@localhost                                                                                    |
+----------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO '<用戶名>'@'localhost' IDENTIFIED BY PASSWORD '*5102144CA406FC026831D796EA07645447677551'  |
| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, INDEX, ALTER, TRIGGER ON `blogproject`.* TO '<用戶名>'@'localhost' |
+----------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

2. 修改Django的配置

2.1. 修改settings.py中數據庫相關

DATABASES = {
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    # }
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'blogproject',        
        'USER': '<用戶名>',
        'PASSWORD': '<用戶名>',
        'HOST': '<數據庫服務器的IP>',
        'PORT': '3306',  # 默認的服務端口號
        'OPTIONS': {
            # 存儲引擎啓用嚴格模式,非法數據值被拒絕
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",  
            'charset': 'utf8mb4',
        },
    }
}

2.2. 安裝mysqlclient

Darwin luizyaodeMacBook-Air.local 18.6.0 Darwin Kernel Version 18.6.0: Thu Apr 25 23:16:27 PDT 2019; root:xnu-4903.261.4~2/RELEASE_X86_64 x86_64

2.2.1. 安裝mysql-connector-c

luizyaodeMacBook-Air:~ luizyao$ brew install mysql-connector-c
==> Downloading https://mirrors.ustc.edu.cn/homebrew-bottles/bottles/mysql-conne
######################################################################## 100.0%
==> Pouring mysql-connector-c-6.1.11.mojave.bottle.tar.gz
🍺  /usr/local/Cellar/mysql-connector-c/6.1.11: 79 files, 15.3MB

2.2.2. 修復mysql-connector-c在mac os的python3的bug

/usr/local/Cellar/mysql-connector-c/6.1.11/bin/mysql_config

# Create options 
libs="-L$pkglibdir"
libs="$libs -l "

修改爲

# Create options 
libs="-L$pkglibdir"
libs="$libs -lmysqlclient -lssl -lcrypto"

2.2.3. 使用pip安裝mysqlclient

[luizyaodeMacBook-Air:django-blog luizyao$ pip3 install mysqlclient

2.2.4. 使用pipenv安裝mysqlclient

這個時候會報錯,因爲:because Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries.

luizyaodeMacBook-Air:django-blog luizyao$ brew info openssl
openssl: stable 1.0.2s (bottled) [keg-only]
SSL/TLS cryptography library
https://openssl.org/
/usr/local/Cellar/openssl/1.0.2s (1,795 files, 12.0MB)
  Poured from bottle on 2019-06-22 at 13:16:17
From: https://mirrors.ustc.edu.cn/homebrew-core.git/Formula/openssl.rb
==> Caveats
A CA file has been bootstrapped using certificates from the SystemRoots
keychain. To add additional certificates (e.g. the certificates added in
the System keychain), place .pem files in
  /usr/local/etc/openssl/certs

and run
  /usr/local/opt/openssl/bin/c_rehash

openssl is keg-only, which means it was not symlinked into /usr/local,
because Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries.

If you need to have openssl first in your PATH run:
  echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile

For compilers to find openssl you may need to set:
  export LDFLAGS="-L/usr/local/opt/openssl/lib"
  export CPPFLAGS="-I/usr/local/opt/openssl/include"

==> Analytics
install: 490,905 (30 days), 1,748,362 (90 days), 6,591,368 (365 days)
install_on_request: 59,162 (30 days), 234,123 (90 days), 884,807 (365 days)
build_error: 0 (30 days)

根據提示做如下操作

luizyaodeMacBook-Air:django-blog luizyao$ echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
luizyaodeMacBook-Air:django-blog luizyao$ source ~/.bash_profile 
luizyaodeMacBook-Air:django-blog luizyao$ export LDFLAGS="-L/usr/local/opt/openssl/lib"
luizyaodeMacBook-Air:django-blog luizyao$ export CPPFLAGS="-I/usr/local/opt/openssl/include"

再安裝mysqlclient,就能成功了

luizyaodeMacBook-Air:django-blog luizyao$ pipenv install mysqlclient
Installing mysqlclient…
Adding mysqlclient to Pipfile's [packages]…
✔ Installation Succeeded 
Pipfile.lock (cee3a5) out of date, updating to (79d06d)…
Locking [dev-packages] dependencies…
✔ Success! 
Locking [packages] dependencies…
✔ Success! 
Updated Pipfile.lock (cee3a5)!
Installing dependencies from Pipfile.lock (cee3a5)…
  🐍   ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 4/4 — 00:00:01
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.

2.3. 執行migrate操作

[luizyaodeMacBook-Air:django-blog luizyao$ pipenv run python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.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 contenttypes.0002_remove_content_type_name... 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 blog.0001_initial... OK
  Applying sessions.0001_initial... OK

只有Applying blog.0001_initial... OK是和我們自己模型相關的,其他的是Django系統自帶的一些模型, 我們可以進一步的查看數據庫到底做了什麼操作;

luizyaodeMacBook-Air:django-blog luizyao$ pipenv run python manage.py sqlmigrate blog 0001
BEGIN;
--
-- Create model Category
--
CREATE TABLE `blog_category` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(100) NOT NULL);
--
-- Create model Tag
--
CREATE TABLE `blog_tag` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(100) NOT NULL);
--
-- Create model Post
--
CREATE TABLE `blog_post` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `title` varchar(70) NOT NULL, `excerpt` varchar(200) NOT NULL, `body` longtext NOT NULL, `created_at` datetime(6) NOT NULL, `modified_at` datetime(6) NOT NULL, `author_id` integer NOT NULL, `category_id` integer NOT NULL);
CREATE TABLE `blog_post_tag` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `post_id` integer NOT NULL, `tag_id` integer NOT NULL);
ALTER TABLE `blog_post` ADD CONSTRAINT `blog_post_author_id_dd7a8485_fk_auth_user_id` FOREIGN KEY (`author_id`) REFERENCES `auth_user` (`id`);
ALTER TABLE `blog_post` ADD CONSTRAINT `blog_post_category_id_c326dbf8_fk_blog_category_id` FOREIGN KEY (`category_id`) REFERENCES `blog_category` (`id`);
ALTER TABLE `blog_post_tag` ADD CONSTRAINT `blog_post_tag_post_id_a5c00319_fk_blog_post_id` FOREIGN KEY (`post_id`) REFERENCES `blog_post` (`id`);
ALTER TABLE `blog_post_tag` ADD CONSTRAINT `blog_post_tag_tag_id_2bbd31e4_fk_blog_tag_id` FOREIGN KEY (`tag_id`) REFERENCES `blog_tag` (`id`);
ALTER TABLE `blog_post_tag` ADD CONSTRAINT `blog_post_tag_post_id_tag_id_ba2a5f83_uniq` UNIQUE (`post_id`, `tag_id`);
COMMIT;

在數據庫中可以看到Django創建的具體表;

MariaDB [blogproject]> show tables;
+----------------------------+
| Tables_in_blogproject      |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| blog_category              |
| blog_post                  |
| blog_post_tag              |
| blog_tag                   |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+
14 rows in set (0.00 sec)

2.4. 創建一個管理員用戶

luizyaodeMacBook-Air:django-blog luizyao$ pipenv run python manage.py createsuperuser
用戶名 (leave blank to use 'luizyao'): luizyao
電子郵件地址: [email protected]
Password: 
Password (again): 
Superuser created successfully.

在數據庫中,我們就可以看到這個管理員用戶了

MariaDB [blogproject]> select * from auth_user;
+----+--------------------------------------------------------------------------------+------------+--------------+----------+------------+-----------+-----------------+----------+-----------+----------------------------+
| id | password                                                                       | last_login | is_superuser | username | first_name | last_name | email           | is_staff | is_active | date_joined                |
+----+--------------------------------------------------------------------------------+------------+--------------+----------+------------+-----------+-----------------+----------+-----------+----------------------------+
|  1 | pbkdf2_sha256$150000$ViP2waofsEQU$3oNPdGxlGPmt5Nbl/lcHJli8V9j7425ZxRfqKF18E0Q= | NULL       |            1 | luizyao  |            |           | [email protected] |        1 |         1 | 2019-08-25 03:49:19.667011 |
+----+--------------------------------------------------------------------------------+------------+--------------+----------+------------+-----------+-----------------+----------+-----------+----------------------------+
1 row in set (0.00 sec)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章