■Django, MySQL初心者のエラー悶絶開発記録 #1 (migrateまで)

スポンサーリンク
DB
スポンサーリンク

開発ってのはエラーとの格闘だ。

プログラムを書いている時間よりエラーと格闘している時間の方が長い。

だから、少しでもエラーと格闘する人を減らすためにこの記事は書かれている。

(※本記事はdjangoをインストールしていることを前提としている記事になっています。)

だから、どや顔で言わせてください。「俺の屍を越えて行け!」

さて、今回やろうとしていることはDjangoとMySQLの接続。

環境としてはwindows上にWSL2を入れて、WSL2上で行っています。

Djangoとは

Djangoとは無料で使えるWebアプリケーションのフレームワークです。

Webアプリケーションを0から作ろうとすると非常に大変ですが、型として用意されたフレームワークを使うことで作成者が低コストでWebアプリケーションを作成できます。

MySQLとは

MySQLとは、SQL データベース管理システムです。詳しくはこちらのドキュメントを読むと理解が深まると思います。

こちらも無料で使用することができます。

構築

では、構築をしていきます。

必要なものをインストール

まずは必要なものをインストール。

$ sudo apt install mysql-server mysql-client

version確認をする。

$ mysql --version
mysql  Ver 8.0.31-0ubuntu0.20.04.1 for Linux on x86_64 ((Ubuntu))

MySQL側の設定

MySQLの初期化を行う。

$ sudo mysql_secure_installation

👹Error: Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)

⚠️ここでこんなエラー出ませんでした?

Error: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

このエラーは可愛いもの。RPGで言えばスライムみたいなもん。

原因は「mysqlが止まっているから」だけ。

僕の場合は以下のように動いていなかった。

$ sudo service mysql status
 * MySQL is stopped.

以下を実行してみて、再度「sudo mysql_secure_installation」を実行するとエラーは消えました。😊(にっこり)

$ sudo service mysql start

次にmysqlの初期設定を行う。以下のコマンドを実行。

$ sudo mysql_secure_installation

👹Failed! Error: SET PASSWORD has no significance for user ‘root’@’localhost’ as the authentication method used doesn’t store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters.

エラーを解消したと安堵した束の間、また問題が発生した。

以下のようなものだ。

New password: 

Re-enter new password: 

Estimated strength of the password: 50 
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
 ... Failed! Error: SET PASSWORD has no significance for user 'root'@'localhost' as the authentication method used doesn't store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters.

長いな。

ようはここだね。

SET PASSWORD has no significance for user 'root'@'localhost' as the authentication method used doesn't store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters.

このエラーについてはこちらのサイトを参考にしました。

🧙これで解決

mysqlに入る。

$ sudo mysql -u root

パスワードを設定する。({password}のところを適宜自分のパスワードにしてね)

⚠️ここでパスワードを設定すると今後mysqlにrootユーザで入るときにパスワードを入力しなくてはならなくなりますので、忘れないようにしましょう。

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by '{password}';
Query OK, 0 rows affected (0.08 sec)

これでmysqlから出て、再度「sudo mysql_secure_installation」を実行すると上手くいく

Django側の設定まで

Djangoで使うDB、ユーザー、パスワードを設定していく。

まずはDBから。

mysql> create database django_db;
Query OK, 1 row affected (0.04 sec)

mysql> show databases;
+-----------------------+
| Database              |
+-----------------------+
| django_db             |
| 【略】                 |
+-----------------------+

続いてユーザー。(test_user, test_passwdのところは適宜自分の値に変えてね)

mysql> create user 'test_user'@'%' identified by 'test_passwd';
Query OK, 0 rows affected (0.10 sec)

mysql> grant all on *.* to test_user@'%';
Query OK, 0 rows affected (0.07 sec)

django側のsetting.pyのDATABASESには以下のように設定

DATABASES = {
    'default': {
        #'ENGINE': 'django.db.backends.sqlite3',
        #'NAME': BASE_DIR / 'db.sqlite3',
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_db',
        'USER': 'test_user',
        'PASSWORD': 'test_passwd',
    }
}

マイグレーション

マイグレーションをしていく。

$ python3 manage.py makemigrations

2002, “Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (13)”

⚠️もしかしてここでこんなエラー出ませんでした?

packages/django/core/management/commands/makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (13)")

ようはこれ。

Got an error checking a consistent migration history performed for database connection 'default': (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (13)")

このエラーが出た時は、そもそも以下のようにdjango→MySQLとの接続を確認したところ同じエラーが発生。(接続そのものができていない)

$ python3 manage.py dbshell
ERROR 2002 (HY0000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (13)'
CommandError: "mysql --user=root --host=localhost test_db" returned non-zero exit status 1.

もしかしてと思ってmysqlコマンドでも以下のように同じエラー

$ mysql
ERROR 2002 (HY0000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (13)'

さらにもしかしてと思ってsudoを付けたら(rootで実行したら)、エラーが消えた

$ sudo mysql

つまりsudo(rootユーザ)で、djangoのsetting.py内のuserがrootの設定ではmigrationが動くと想定される。

しかし、pip3ではsudoでインストールしていないものもあり、さらに作業はrootユーザでやらない方が今後のセキュリティ的な意味も考えるといいと思ったため、djangoのsetting.py内の設定を変える方向にするのがいいように思えた。

🧙これで解決

上記で行った以下の処理を行っていないと今回のようなエラーが発生する。

mysql> create user 'test_user'@'%' identified by 'test_passwd';
Query OK, 0 rows affected (0.10 sec)

mysql> grant all on *.* to test_user@'%';
Query OK, 0 rows affected (0.07 sec)

この設定をして再度マイグレーション(「python3 manage.py makemigrations」を実行)するとエラーは出なくなった。

migrateする

$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, 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 auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

うまくいきましたね。

このとき心の底からガッツポーズした。

【おさらい】今回格闘し、討伐したエラー達👹

Error: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

... Failed! Error: SET PASSWORD has no significance for user 'root'@'localhost' as the authentication method used doesn't store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters.

Got an error checking a consistent migration history performed for database connection 'default': (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (13)")

タイトルとURLをコピーしました