django + mysql メモ

環境

software version
amazon linux 2018.03
python 3.7.3
django 2.2.1
mysql 5.7

DjangoMySQLを接続するにあたって公式の推奨に従い、mysqlclientを選択する。

docs.djangoproject.com

python の設定

以下を参考に実施する。

danieleriksson.net

パッケージをダウンロードする。

$ curl -O https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tar.xz

解凍する。

$ tar -Jxvf Python-3.7.3.tar.xz

コンパイラとライブラリの導入。

[ec2-user@ip-xx-xx-1-192 Python-3.7.3]$ sudo yum groupinstall "Development Tools"

libffi-develが参考記事のコマンドには含まれていないが、必要なため追記。

$ sudo yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel expat-devel libffi-devel

コンパイラが無いとビルド時にエラーになる。

[ec2-user@ip-xx-xx-1-192 Python-3.7.3]$ ./configure
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking for python3.7... no
checking for python3... no
checking for python... python
checking for --enable-universalsdk... no
checking for --with-universal-archs... no
checking MACHDEP... checking for --without-gcc... no
checking for --with-icc... no
checking for gcc... no
checking for cc... no
checking for cl.exe... no
configure: error: in `/home/ec2-user/Python-3.7.3':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details
[ec2-user@ip-xx-xx-1-192 Python-3.7.3]$

stackoverflow.com

ビルドする。

[ec2-user@ip-xx-xx-1-192 ~]$ cd Python-3.7.3
[ec2-user@ip-xx-xx-1-192 Python-3.7.3]$ sudo ./configure --prefix=/usr/local --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
[ec2-user@ip-xx-xx-1-192 Python-3.7.3]$ sudo make && make altinstall
[ec2-user@ip-xx-xx-1-192 Python-3.7.3]$ sudo make altinstall

python3.7 で実行できるようになる。

[ec2-user@ip-xx-xx-1-192 Python-3.7.3]$ which python3.7
/usr/local/bin/python3.7

pip3.7 も利用可能になっている。

[ec2-user@ip-xx-xx-1-192 bin]$ which pip3.7
/usr/local/bin/pip3.7

シンボリックリンク設定

python3.7 を python3 で実行できるようにしたいので、シンボリックリンクを設定する。

$ sudo ln -s /usr/local/bin/python3.7 python3
[ec2-user@ip-xx-xx-1-192 ~]$ python3
Python 3.7.3 (default, May 13 2019, 02:47:06)
[GCC 7.2.1 20170915 (Red Hat 7.2.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

pip3.7 も pip3 で実行できるようにする。

$ sudo ln -s /usr/local/bin/pip3.7 pip3
[ec2-user@ip-xx-xx-1-192 ~]$ pip3 list
Package    Version
---------- -------
pip        19.0.3
setuptools 40.8.0
You are using pip version 19.0.3, however version 19.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

django の設定

django の導入。

$ sudo pip3 install django

プロジェクトの作成。

my_projectという名前のプロジェクトを作成することにした。

[ec2-user@ip-xx-xx-1-192 ~]$ django-admin startproject my_project

setting.pyの設定。

setting.py を編集するためディレクトリを移動する。

[ec2-user@ip-xx-xx-1-192 ~]$ cd my_project/my_project/
[ec2-user@ip-xx-xx-1-192 my_project]$ ll
total 12
-rw-r--r-- 1 ec2-user ec2-user    0 May 13 04:39 __init__.py
-rw-r--r-- 1 ec2-user ec2-user 3117 May 13 04:44 settings.py
-rw-r--r-- 1 ec2-user ec2-user  752 May 13 04:39 urls.py
-rw-r--r-- 1 ec2-user ec2-user  397 May 13 04:39 wsgi.py
[ec2-user@ip-xx-xx-1-192 my_project]$

settings.py の変更箇所は以下の通り。

ALLOWED_HOSTS = ['xxx.xxx.xxx.19']  # public ip を入力

LANGUAGE_CODE = 'ja'

TIME_ZONE = 'Asia/Tokyo'

mysql5.7 の設定

amazon linux のため el6 を選択する。

mysql80のリポジトリ追加

[ec2-user@ip-xx-xx-1-192 my_project]$ sudo yum localinstall https://dev.mysql.com/get/mysql80-community-release-el6-3.noarch.rpm

mysql8.0 のリポジトリを無効化

[ec2-user@ip-xx-xx-1-192 my_project]$ sudo yum-config-manager --disable mysql80-community

mysql5.7 のリポジトリを有効化

[ec2-user@ip-xx-xx-1-192 my_project]$ sudo yum-config-manager --enable mysql57-community

mysql57 の情報が確認できるようになる。

[ec2-user@ip-xx-xx-1-192 my_project]$ yum info mysql-community-server
Loaded plugins: priorities, update-motd, upgrade-helper
mysql-connectors-community                                                           | 2.5 kB  00:00:00
mysql-tools-community                                                                | 2.5 kB  00:00:00
mysql57-community                                                                    | 2.5 kB  00:00:00
mysql57-community/x86_64/primary_db                                                  | 182 kB  00:00:00
24 packages excluded due to repository priority protections
Available Packages
Name        : mysql-community-server
Arch        : x86_64
Version     : 5.7.26
Release     : 1.el6
Size        : 153 M
Repo        : mysql57-community/x86_64
Summary     : A very fast and reliable SQL database server
URL         : http://www.mysql.com/
License     : Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. Under GPLv2
            : license as shown in the Description field.
Description : The MySQL(TM) software delivers a very fast, multi-threaded, multi-user,
            : and robust SQL (Structured Query Language) database server. MySQL Server
            : is intended for mission-critical, heavy-load production systems as well
            : as for embedding into mass-deployed software. MySQL is a trademark of
            : Oracle and/or its affiliates
            :
            : The MySQL software has Dual Licensing, which means you can use the MySQL
            : software free of charge under the GNU General Public License
            : (http://www.gnu.org/licenses/). You can also purchase commercial MySQL
            : licenses from Oracle and/or its affiliates if you do not wish to be bound by the terms of
            : the GPL. See the chapter "Licensing and Support" in the manual for
            : further info.
            :
            : The MySQL web site (http://www.mysql.com/) provides the latest news and
            : information about the MySQL software.  Also please see the documentation
            : and the manual for more information.
            :
            : This package includes the MySQL server binary as well as related utilities
            : to run and administer a MySQL server.

mysql-devel の導入

[ec2-user@ip-xx-xx-1-192 my_project]$ sudo yum install mysql57-devel.x86_64

mysql57の導入

[ec2-user@ip-xx-xx-1-192 my_project]$ sudo yum install mysql-community-server
[ec2-user@ip-xx-xx-1-192 my_project]$ mysql --version
mysql  Ver 14.14 Distrib 5.7.26, for Linux (x86_64) using  EditLine wrapper
[ec2-user@ip-xx-xx-1-192 my_project]$ yum list installed | grep mysql
mysql-community-client.x86_64    5.7.26-1.el6                 @mysql57-community
mysql-community-common.x86_64    5.7.26-1.el6                 @mysql57-community
mysql-community-devel.x86_64     5.7.26-1.el6                 @mysql57-community
mysql-community-libs.x86_64      5.7.26-1.el6                 @mysql57-community
mysql80-community-release.noarch el6-3                        installed
[ec2-user@ip-xx-xx-1-192 my_project]$

mysql-devel が無いと後述する mysqlclient のインストールや django の makemigrations がエラーになる

[ec2-user@ip-xx-xx-1-192 my_project]$ sudo pip3 install mysqlclient
Collecting mysqlclient
  Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz
    ERROR: Complete output from command python setup.py egg_info:
    ERROR: /bin/sh: mysql_config: command not found
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-wvc2e8ay/mysqlclient/setup.py", line 16, in <module>
        metadata, options = get_config()
      File "/tmp/pip-install-wvc2e8ay/mysqlclient/setup_posix.py", line 51, in get_config
        libs = mysql_config("libs")
      File "/tmp/pip-install-wvc2e8ay/mysqlclient/setup_posix.py", line 29, in mysql_config
        raise EnvironmentError("%s not found" % (_mysql_config_path,))
    OSError: mysql_config not found
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-wvc2e8ay/mysqlclient/
[ec2-user@ip-xx-xx-1-192 my_project]$
[ec2-user@ip-xx-xx-1-192 my_project]$python3.7 manage.py makemigrations
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module>
    import MySQLdb as Database
ModuleNotFoundError: No module named 'MySQLdb'

(途中省略)

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?
[ec2-user@ip-xx-xx-1-192 my_project]$

参考 qiita.com

※mysql57 をインストールしてから mysql-devel をインストールしようとすると、バージョンに起因するエラーが出た。インストールした mysql をアンインストールして、mysql-devel ⇒ mysql57 の順番でインストールするとバージョンの問題を解消できた。

[ec2-user@ip-xx-xx-1-192 my_project]$ sudo yum install mysql57-devel
Loaded plugins: priorities, update-motd, upgrade-helper
amzn-main                                                                            | 2.1 kB  00:00:00
amzn-updates                                                                         | 2.5 kB  00:00:00
24 packages excluded due to repository priority protections
Resolving Dependencies
--> Running transaction check
---> Package mysql57-devel.x86_64 0:5.7.25-1.11.amzn1 will be installed
--> Processing Dependency: mysql57-libs(x86-64) = 5.7.25-1.11.amzn1 for package: mysql57-devel-5.7.25-1.11.amzn1.x86_64
--> Processing Dependency: mysql57(alternatives) for package: mysql57-devel-5.7.25-1.11.amzn1.x86_64
--> Processing Dependency: mysql57(alternatives) for package: mysql57-devel-5.7.25-1.11.amzn1.x86_64
--> Processing Dependency: libmysqlclient.so.1020()(64bit) for package: mysql57-devel-5.7.25-1.11.amzn1.x86_64
--> Running transaction check
---> Package mysql57.x86_64 0:5.7.25-1.11.amzn1 will be installed
--> Processing Dependency: mysql57-common(x86-64) = 5.7.25-1.11.amzn1 for package: mysql57-5.7.25-1.11.amzn1.x86_64
---> Package mysql57-libs.x86_64 0:5.7.25-1.11.amzn1 will be installed
--> Running transaction check
---> Package mysql57-common.x86_64 0:5.7.25-1.11.amzn1 will be installed
--> Processing Dependency: mysql-config for package: mysql57-common-5.7.25-1.11.amzn1.x86_64
--> Running transaction check
---> Package mysql-config.x86_64 0:5.5.62-1.23.amzn1 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

============================================================================================================
 Package                    Arch               Version                       Repository                Size
============================================================================================================
Installing:
 mysql57-devel              x86_64             5.7.25-1.11.amzn1             amzn-updates             293 k
Installing for dependencies:
 mysql-config               x86_64             5.5.62-1.23.amzn1             amzn-updates              49 k
 mysql57                    x86_64             5.7.25-1.11.amzn1             amzn-updates              14 M
 mysql57-common             x86_64             5.7.25-1.11.amzn1             amzn-updates              90 k
 mysql57-libs               x86_64             5.7.25-1.11.amzn1             amzn-updates             1.2 M

Transaction Summary
============================================================================================================
Install  1 Package (+4 Dependent packages)

Total size: 15 M
Installed size: 49 M
Is this ok [y/d/N]: y
Downloading packages:
Running transaction check
Running transaction test


Transaction check error:
  file /etc/my.cnf from install of mysql-config-5.5.62-1.23.amzn1.x86_64 conflicts with file from package mysql-community-server-5.7.26-1.el6.x86_64

Error Summary
-------------

[ec2-user@ip-xx-xx-1-192 my_project]$

mysqlclient の導入

$ sudo pip3 install mysqlclient

pypi.org

mysql57-server の導入

[ec2-user@ip-xx-xx-1-192 my_project]$ yum install mysql57-server

サービスの開始

[ec2-user@ip-xx-xx-1-192 my_project]$ sudo service mysqld start

Starting mysqld:                                           [  OK  ]

ログイン

[ec2-user@ip-xx-xx-1-192 my_project]$ mysql -u root

DB 作成

mysql> CREATE DATABASE my_project;
Query OK, 1 row affected (0.00 sec)

mysql>
mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| my_project         |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.01 sec)

mysql>

setting.py に以下変更を反映。

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

マイグレーション実行

[ec2-user@ip-xx-xx-1-192 my_project]$ python3 manage.py makemigrations
[ec2-user@ip-xx-xx-1-192 my_project]$ python3 manage.py migrate