参考
この Udemy の講座の通りに
Django を pip でローカルでインストールして
MySQL Community で MySQL もローカルにインストールして
===
MySQL をインストールする
GUI アプリの MySQL Community の Mac 版がないのを確認
Mac の場合は workbench がない?ので
Rosetta を切って Arm 64 で入れる必要がある
brew でインストール
brew install mysql
==> Installing mysql
==> Pouring mysql--8.0.26.arm64_big_sur.bottle.1.tar.gz
==> /opt/homebrew/Cellar/mysql/8.0.26/bin/mysqld --initialize-insecure --user=ka
==> Caveats
We've installed your MySQL database without a root password. To secure it run:
mysql_secure_installation
MySQL is configured to only allow connections from localhost by default
To connect run:
mysql -uroot
To start mysql:
brew services start mysql
起動時の pid エラーを解決
起動できなかった。なので権限を与えて解決。
https://kei-s-lifehack.hatenablog.com/entry/resolved-mysql-pid-error
詳細はこの記事に。
MySQL を cli で起動確認
mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.26 Homebrew
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
これで起動できた。
venv と pip で REST Framework と Cors Headers を入れる
当然として Django はインストールしておく
source django-test/bin/activate
(django-test) kaede0902@rooter code %
事前に用意しておいた仮想環境 venv を起動
ここで pip install する
pip install djangorestframework
Collecting djangorestframework
Using cached djangorestframework-3.12.4-py3-none-any.whl (957 kB)
Requirement already satisfied: django>=2.2 in ./django-test/lib/python3.9/site-packages (from djangorestframework) (3.2.7)
Requirement already satisfied: asgiref<4,>=3.3.2 in ./django-test/lib/python3.9/site-packages (from django>=2.2->djangorestframework) (3.4.1)
Requirement already satisfied: sqlparse>=0.2.2 in ./django-test/lib/python3.9/site-packages (from django>=2.2->djangorestframework) (0.4.2)
Requirement already satisfied: pytz in ./django-test/lib/python3.9/site-packages (from django>=2.2->djangorestframework) (2021.1)
Installing collected packages: djangorestframework
Successfully installed djangorestframework-3.12.4
成功。
pip install django-cors-headers
Collecting django-cors-headers
Downloading django_cors_headers-3.8.0-py3-none-any.whl (12 kB)
Requirement already satisfied: Django>=2.2 in ./django-test/lib/python3.9/site-packages (from django-cors-headers) (3.2.7)
Requirement already satisfied: sqlparse>=0.2.2 in ./django-test/lib/python3.9/site-packages (from Django>=2.2->django-cors-headers) (0.4.2)
Requirement already satisfied: asgiref<4,>=3.3.2 in ./django-test/lib/python3.9/site-packages (from Django>=2.2->django-cors-headers) (3.4.1)
Requirement already satisfied: pytz in ./django-test/lib/python3.9/site-packages (from Django>=2.2->django-cors-headers) (2021.1)
Installing collected packages: django-cors-headers
Successfully installed django-cors-headers-3.8.0
成功
--
django-admin startproject で DjangoAPI のプロジェクトを作成
django-admin startproject DjangoAPI
ls
DjangoAPI django-test djangoProject editors react-router
作成成功
manage.py runserver で先ほど作った Django プロジェクトの動作確認をする
manage.py runserver
動いた
manage.py startapp で Django アプリを作る
manage.py startapp EmployeeApp
これで被雇用者アプリが作成された
DjangoAPI/setting.py/INSTALLED_APPS にインストールしたライブラリと作成したアプリ名を記入
大元の DjangoAPI のディレクトリの setting.py を編集
インストール済みのアプリの配列を更新する
INSTALLED_APPS = [
'django.contrib.admin',
'rest_framework',
'corsheaders',
'Employeeapp.apps.EmployeeappConfig',
]
先ほど入れたライブラリの rest_framework
と corsheaders
作成したアプリ EmployeeApp の app.py に記載されている EmployeeappConfig
を読み込むために Employeeapp.apps.EmployeeappConfig
この行を今の INSTALLED_APPS
に追記する
DjangoAPI/setting.py/MIDDLEWARE に cors headers の情報を記載
こちらも同様にして ライブラリとアプリの情報を追加する
CORS_ORIGIN_ALLOW_ALL = True
デバック用のアクセス設定を全て True にする
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleWare',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ミドルウェアでは corsheaders のみを追加。
MySQL で DB を作成
mysql> create database mytestdb
-> ;
Query OK, 1 row affected (0.02 sec)
pip で pymysql という Django に MySQL をつなぐライブラリを入れる
pip install pymysql
Collecting pymysql
Downloading PyMySQL-1.0.2-py3-none-any.whl (43 kB)
|████████████████████████████████| 43 kB 2.0 MB/s
Installing collected packages: pymysql
Successfully installed pymysql-1.0.2
EmployeeApp/models.py
class Departments(models.Model):
DepartmentId = models.AutoField(primary_key=True)
DepartmentName = models.CharField(max_length=500)
class Employees(models.Model):
EmployeeId = models.AutoField(primary_key=True)
EmployeeName = models.CharField(max_length=500)
Department= models.CharField(max_length=500)
DateOfString = models.DateField()
PhotoFileName = models.CharField(max_length=500)
udemy の通りに
部門の id と 名前
被雇用者の id, 名前, 部門, 加入日付, アイコンのファイル名,
これらのモデルを作成する
settings.py/DATABASE で MySQL のエンジン情報を記載する
backend の DB の状態を記入
import pymysql
pymysql.install_as_MySQLdb()
まず直前の行で pymysql のライブラリを import する
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
最初はこの状態。
このエンジンと名前を変更する。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mytestdb',
'USER': 'testmyadmin@mytestsql',
'PASSWORD': '1234',
'HOST': 'localhost',
'PORT': '3306'
}
}
エンジンや名前は自明。
user と password はこれはこの名前が作成されるようになるのだろうか?
host と port は動画の人は azure の db を使っていたのでどうするか不明
stackoverflow の通りに my.conf のデフォルトを書く
公式ドキュメントを探してみる
詳しく書いてない
https://stackoverflow.com/questions/19189813/setting-django-up-to-use-mysql
しかしこれが詳しい。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB_NAME',
'USER': 'DB_USER',
'PASSWORD': 'DB_PASSWORD',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
'OPTIONS': {
'read_default_file': '/path/to/my.cnf',
},
}
}
ローカル DB の場合はエンジン、ポートは同じだがが他が違う。
HOST は localhost で
名前、ユーザー、パスワード、が規定の DB_*
の変数名?になる
さらに options として mysql の cnf も書く必要がありそう。
my.conf の正しい位置を探して settings.py を更新
https://stackoverflow.com/a/10757312
まず my.conf の場所を探す。
mysql --help or mysql --help | grep my.cnf
order of preference, my.cnf, $MYSQL_TCP_PORT,
/etc/my.cnf /etc/mysql/my.cnf /opt/homebrew/etc/my.cnf ~/.my.cnf
kaede0902@rooter ~ % ls /opt/homebrew/etc
bash_completion.d my.cnf openssl@1.1
homebrew で入れたし homebrew にあった。
# Default Homebrew MySQL server config
[mysqld]
# Only allow connections from localhost
bind-address = 127.0.0.1
mysqlx-bind-address = 127.0.0.1
デフォルトではこうなっていた。
https://stackoverflow.com/a/19189930
先ほどの django settings の記事。
You also need to create the /path/to/my.cnf file with similar settings from above
[client]
database = DB_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8
sudo vi で開いて内容はこれを書く。
db, user, pass, は settings.py と同じ変数。
'OPTIONS': {
'read_default_file': '/opt/homebrew/etc/my.cnf',
},
そして settings.py に忘れずに読み込み先として書く。
Django サーバーを再度起動するが、 MySQL サーバーに接続できない
django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 61] Connection refused)")
migrate もできない
options を潰してもだめ
あ、デフォルト
password を空にしてもダメ
mysqlclient をインストールして試す
https://code-database.com/knowledges/101
mysql client がそもそも必要らしい。
この記事によると、static file が必要だが、多分今回は必要ない
ALLOWED_HOSTS = ['your server IP address']
許可されたホストが必要らしい。
とりあえず localhost を追加してみるがダメだった
Step 4 — Install MySQL Database Connector
python3-dev libmysqlclient-dev default-libmysqlclient-dev
これらのライブラリをインストールする
必要か? -dev は絶対いらなそう
mysql client だけにしてみる
pip install mysqlclient
Collecting mysqlclient
Downloading mysqlclient-2.0.3.tar.gz (88 kB)
|████████████████████████████████| 88 kB 2.3 MB/s
Using legacy 'setup.py install' for mysqlclient, since package 'wheel' is not installed.
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient ... done
Successfully installed mysqlclient-2.0.3
wheel はダメだったが他は入ったようだ。
mysql 叩いてみたら再度起動できないエラーが出た
/tmp/mysql.sock に権限を与える
https://hituzi-ando.hatenablog.com/entry/2020/01/24/065731
権限がとにかく足りなっぽい?
chown で tmp/ のソケットファイルは _mysql の所有にした。
sudo chmod 755 /tmp/mysql.sock
権限を与える
これでもダメだった
まとめ
設定がうまくいかずに Django から MySQL サーバーが読めなかった
ローカルでやるのを諦めて Docker コンテナでやる
Top comments (0)