当前位置:Gxlcms > 数据库问题 > Django系列---使用MySql数据库

Django系列---使用MySql数据库

时间:2021-07-01 10:21:17 帮助过:3人阅读

目录

  • 1. 创建数据库
    • 1.1. 使用utf8mb4编码
      • 1.1.1. 确定mysql的配置文件
      • 1.1.2. 修改配置文件
      • 1.1.3. 重启数据库服务,检查相关字段
      • 1.1.4. 新建数据库
    • 1.2. 使用已经存在的数据库
      • 1.2.1. 修改已有数据库的编码
    • 1.3. 为Django项目新建一个数据库用户
  • 2. 修改Django的配置
    • 2.1. 修改settings.py中数据库相关
    • 2.2. 安装mysqlclient
      • 2.2.1. 安装mysql-connector-c
      • 2.2.2. 修复mysql-connector-c在mac os的python3的bug
      • 2.2.3. 安装mysqlclient
    • 2.3. 执行migrate操作
    • 2.4. 创建一个管理员用户
  • 3. 拓展阅读

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的配置文件

  1. <code># 系统中my.cnf文件的位置
  2. [luizyao@VM_0_15_centos ~]$ locate my.cnf
  3. /etc/my.cnf
  4. /etc/my.cnf.d
  5. /etc/my.cnf.d/client.cnf
  6. /etc/my.cnf.d/mysql-clients.cnf
  7. /etc/my.cnf.d/server.cnf
  8. # mysql启动时,读取配置文件的目录顺序
  9. [luizyao@VM_0_15_centos ~]$ mysql --help | grep 'my.cnf'
  10. /etc/mysql/my.cnf /etc/my.cnf ~/.my.cnf
  11. order of preference, my.cnf, $MYSQL_TCP_PORT,</code>

1.1.2. 修改配置文件

/etc/my.cnf

  1. <code>[client]
  2. default-character-set = utf8mb4
  3. [mysql]
  4. default-character-set = utf8mb4
  5. [mysqld]
  6. # Settings user and group are ignored when systemd is used.
  7. # If you need to run mysqld under a different user or group,
  8. # customize your systemd unit file for mariadb according to the
  9. # instructions in http://fedoraproject.org/wiki/Systemd
  10. character-set-client-handshake = FALSE
  11. character-set-server = utf8mb4
  12. collation-server = utf8mb4_unicode_ci
  13. init_connect='SET NAMES utf8mb4'</code>

1.1.3. 重启数据库服务,检查相关字段

  1. <code># 保证character_set_client、character_set_connection、character_set_database、character_set_results和character_set_server的值一定是utf8mb4
  2. MariaDB [(none)]> SHOW VARIABLES WHERE Variable_name LIKE 'character_set_%' OR Variable_name LIKE 'collation%';
  3. +--------------------------+----------------------------+
  4. | Variable_name | Value |
  5. +--------------------------+----------------------------+
  6. | character_set_client | utf8mb4 |
  7. | character_set_connection | utf8mb4 |
  8. | character_set_database | utf8mb4 |
  9. | character_set_filesystem | binary |
  10. | character_set_results | utf8mb4 |
  11. | character_set_server | utf8mb4 |
  12. | character_set_system | utf8 |
  13. | character_sets_dir | /usr/share/mysql/charsets/ |
  14. | collation_connection | utf8mb4_unicode_ci |
  15. | collation_database | utf8mb4_unicode_ci |
  16. | collation_server | utf8mb4_unicode_ci |
  17. +--------------------------+----------------------------+
  18. 11 rows in set (0.02 sec)</code>

1.1.4. 新建数据库

  1. <code>MariaDB [(none)]> create database blogproject;
  2. Query OK, 1 row affected (0.01 sec)
  3. --查看blogproject创建时候使用的编码,回显中注释的部分可以看出,使用的是utf8mb4编码
  4. MariaDB [mysql]> show create database blogproject;
  5. +-------------+----------------------------------------------------------------------------------------------------+
  6. | Database | Create Database |
  7. +-------------+----------------------------------------------------------------------------------------------------+
  8. | blogproject | CREATE DATABASE `blogproject` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */ |
  9. +-------------+----------------------------------------------------------------------------------------------------+
  10. 1 row in set (0.00 sec)</code>

1.2. 使用已经存在的数据库

1.2.1. 修改已有数据库的编码

  1. <code>MariaDB [(none)]> alter database blogproject character set utf8mb4;</code>

1.3. 为Django项目新建一个数据库用户

  1. <code>-- 赋予这个新用户增删改查等权限,不授予drop的权限;并且,只允许本地客户端登陆;
  2. MariaDB [mysql]> grant alter,create,delete,index,insert,select,update,trigger on blogproject.* to <用户名>@localhost identified by '<密码>';
  3. Query OK, 0 rows affected (0.04 sec)
  4. MariaDB [mysql]> flush privileges;
  5. Query OK, 0 rows affected (0.03 sec)
  6. -- 检查权限,秘密默认是加密存储
  7. MariaDB [blogproject]> show grants for <用户名>@localhost;
  8. +----------------------------------------------------------------------------------------------------------------+
  9. | Grants for <用户名>@localhost |
  10. +----------------------------------------------------------------------------------------------------------------+
  11. | GRANT USAGE ON *.* TO '<用户名>'@'localhost' IDENTIFIED BY PASSWORD '*5102144CA406FC026831D796EA07645447677551' |
  12. | GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, INDEX, ALTER, TRIGGER ON `blogproject`.* TO '<用户名>'@'localhost' |
  13. +----------------------------------------------------------------------------------------------------------------+
  14. 2 rows in set (0.00 sec)</code>

2. 修改Django的配置

2.1. 修改settings.py中数据库相关

  1. <code>DATABASES = {
  2. # 'default': {
  3. # 'ENGINE': 'django.db.backends.sqlite3',
  4. # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
  5. # }
  6. 'default': {
  7. 'ENGINE': 'django.db.backends.mysql',
  8. 'NAME': 'blogproject',
  9. 'USER': '<用户名>',
  10. 'PASSWORD': '<用户名>',
  11. 'HOST': '<数据库服务器的IP>',
  12. 'PORT': '3306', # 默认的服务端口号
  13. 'OPTIONS': {
  14. # 存储引擎启用严格模式,非法数据值被拒绝
  15. 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
  16. 'charset': 'utf8mb4',
  17. },
  18. }
  19. }</code>

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

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

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

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

  1. <code># Create options
  2. libs="-L$pkglibdir"
  3. libs="$libs -l "</code>

修改为

  1. <code># Create options
  2. libs="-L$pkglibdir"
  3. libs="$libs -lmysqlclient -lssl -lcrypto"</code>

2.2.3. 安装mysqlclient

2.2.3.1. 使用pip安装

  1. <code>[luizyaodeMacBook-Air:django-blog luizyao$ pip3 install mysqlclient</code>

2.2.3.2. 使用pipenv安装

这个时候会报错,因为:because Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries.

  1. <code>luizyaodeMacBook-Air:django-blog luizyao$ brew info openssl
  2. openssl: stable 1.0.2s (bottled) [keg-only]
  3. SSL/TLS cryptography library
  4. https://openssl.org/
  5. /usr/local/Cellar/openssl/1.0.2s (1,795 files, 12.0MB)
  6. Poured from bottle on 2019-06-22 at 13:16:17
  7. From: https://mirrors.ustc.edu.cn/homebrew-core.git/Formula/openssl.rb
  8. ==> Caveats
  9. A CA file has been bootstrapped using certificates from the SystemRoots
  10. keychain. To add additional certificates (e.g. the certificates added in
  11. the System keychain), place .pem files in
  12. /usr/local/etc/openssl/certs
  13. and run
  14. /usr/local/opt/openssl/bin/c_rehash
  15. openssl is keg-only, which means it was not symlinked into /usr/local,
  16. because Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries.
  17. If you need to have openssl first in your PATH run:
  18. echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
  19. For compilers to find openssl you may need to set:
  20. export LDFLAGS="-L/usr/local/opt/openssl/lib"
  21. export CPPFLAGS="-I/usr/local/opt/openssl/include"
  22. ==> Analytics
  23. install: 490,905 (30 days), 1,748,362 (90 days), 6,591,368 (365 days)
  24. install_on_request: 59,162 (30 days), 234,123 (90 days), 884,807 (365 days)
  25. build_error: 0 (30 days)</code>

根据提示做如下操作

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

再安装mysqlclient,就能成功了

  1. <code>luizyaodeMacBook-Air:django-blog luizyao$ pipenv install mysqlclient
  2. Installing mysqlclient…
  3. Adding mysqlclient to Pipfile's [packages]…
  4. ? Installation Succeeded
  5. Pipfile.lock (cee3a5) out of date, updating to (79d06d)…
  6. Locking [dev-packages] dependencies…
  7. ? Success!
  8. Locking [packages] dependencies…
  9. ? Success!
  10. Updated Pipfile.lock (cee3a5)!
  11. Installing dependencies from Pipfile.lock (cee3a5)…
  12. ?? ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 4/4 — 00:00:01
  13. To activate this project's virtualenv, run pipenv shell.
  14. Alternatively, run a command inside the virtualenv with pipenv run.
  15. </code>

2.3. 执行migrate操作

  1. <code>[luizyaodeMacBook-Air:django-blog luizyao$ pipenv run python manage.py migrate
  2. Operations to perform:
  3. Apply all migrations: admin, auth, blog, contenttypes, sessions
  4. Running migrations:
  5. Applying contenttypes.0001_initial... OK
  6. Applying auth.0001_initial... OK
  7. Applying admin.0001_initial... OK
  8. Applying admin.0002_logentry_remove_auto_add... OK
  9. Applying admin.0003_logentry_add_action_flag_choices... OK
  10. Applying contenttypes.0002_remove_content_type_name... OK
  11. Applying auth.0002_alter_permission_name_max_length... OK
  12. Applying auth.0003_alter_user_email_max_length... OK
  13. Applying auth.0004_alter_user_username_opts... OK
  14. Applying auth.0005_alter_user_last_login_null... OK
  15. Applying auth.0006_require_contenttypes_0002... OK
  16. Applying auth.0007_alter_validators_add_error_messages... OK
  17. Applying auth.0008_alter_user_username_max_length... OK
  18. Applying auth.0009_alter_user_last_name_max_length... OK
  19. Applying auth.0010_alter_group_name_max_length... OK
  20. Applying auth.0011_update_proxy_permissions... OK
  21. Applying blog.0001_initial... OK
  22. Applying sessions.0001_initial... OK</code>

只有Applying blog.0001_initial... OK是和我们自己模型相关的,其他的是Django系统自带的一些模型, 我们可以进一步的查看数据库到底做了什么操作;

  1. <code>luizyaodeMacBook-Air:django-blog luizyao$ pipenv run python manage.py sqlmigrate blog 0001
  2. BEGIN;
  3. --
  4. -- Create model Category
  5. --
  6. CREATE TABLE `blog_category` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(100) NOT NULL);
  7. --
  8. -- Create model Tag
  9. --
  10. CREATE TABLE `blog_tag` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(100) NOT NULL);
  11. --
  12. -- Create model Post
  13. --
  14. 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);
  15. CREATE TABLE `blog_post_tag` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `post_id` integer NOT NULL, `tag_id` integer NOT NULL);
  16. ALTER TABLE `blog_post` ADD CONSTRAINT `blog_post_author_id_dd7a8485_fk_auth_user_id` FOREIGN KEY (`author_id`) REFERENCES `auth_user` (`id`);
  17. ALTER TABLE `blog_post` ADD CONSTRAINT `blog_post_category_id_c326dbf8_fk_blog_category_id` FOREIGN KEY (`category_id`) REFERENCES `blog_category` (`id`);
  18. 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`);
  19. 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`);
  20. ALTER TABLE `blog_post_tag` ADD CONSTRAINT `blog_post_tag_post_id_tag_id_ba2a5f83_uniq` UNIQUE (`post_id`, `tag_id`);
  21. COMMIT;</code>

在数据库中可以看到Django创建的具体表;

  1. <code>MariaDB [blogproject]> show tables;
  2. +----------------------------+
  3. | Tables_in_blogproject |
  4. +----------------------------+
  5. | auth_group |
  6. | auth_group_permissions |
  7. | auth_permission |
  8. | auth_user |
  9. | auth_user_groups |
  10. | auth_user_user_permissions |
  11. | blog_category |
  12. | blog_post |
  13. | blog_post_tag |
  14. | blog_tag |
  15. | django_admin_log |
  16. | django_content_type |
  17. | django_migrations |
  18. | django_session |
  19. +----------------------------+
  20. 14 rows in set (0.00 sec)</code>

2.4. 创建一个管理员用户

  1. <code>luizyaodeMacBook-Air:django-blog luizyao$ pipenv run python manage.py createsuperuser
  2. 用户名 (leave blank to use 'luizyao'): luizyao
  3. 电子邮件地址: luizyao@163.com
  4. Password:
  5. Password (again):
  6. Superuser created successfully.</code>

在数据库中,我们就可以看到这个管理员用户了

  1. <code>MariaDB [blogproject]> select * from auth_user;
  2. +----+--------------------------------------------------------------------------------+------------+--------------+----------+------------+-----------+-----------------+----------+-----------+----------------------------+
  3. | id | password | last_login | is_superuser | username | first_name | last_name | email | is_staff | is_active | date_joined |
  4. +----+--------------------------------------------------------------------------------+------------+--------------+----------+------------+-----------+-----------------+----------+-----------+----------------------------+
  5. | 1 | pbkdf2_sha256$150000$ViP2waofsEQU$3oNPdGxlGPmt5Nbl/lcHJli8V9j7425ZxRfqKF18E0Q= | NULL | 1 | luizyao | | | luizyao@163.com | 1 | 1 | 2019-08-25 03:49:19.667011 |
  6. +----+--------------------------------------------------------------------------------+------------+--------------+----------+------------+-----------+-----------------+----------+-----------+----------------------------+
  7. 1 row in set (0.00 sec)</code>

3. 拓展阅读

  • mysqlclient on pipy
  • mysql_config --libs of mysql-connector/c 6.1.0 on macOS is wrong

Django系列---使用MySql数据库

标签:mail   提示   aries   ring   error:   ike   其他   lin   odi   

人气教程排行