ヒスねこTechBlog

日々の気になる技術をまとめてます。

FlaskとMySQL触ったメモ

Ubuntu20.04で動かしたときのメモです。

環境構築

pipでFlaskを入れるだけですが、Flaskの拡張機能であるflask-sqlalchemyとflask-migrate、flask-wtfも追加で入れました。

$ pip3 install flask flask-sqlalchemy flask-migrate \
flask-wtf email-validator flask-login PyMySQL

DBとしてMySQLを使いたかったので、必要なものをインストールします。

$ sudo apt install mysql-server mysql-client python3-mysqldb

MySQLの初期設定を行います。好みの設定があれば適宜変更してください。

$ sudo mysql_secure_installation
Press y|Y for Yes, any other key for No: y
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 2
New password: 

Re-enter new password: 

Estimated strength of the password: 100 
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.

途中で↑のように怒られた場合はDo you wish~のところでCtrl+Cを押すと抜け出せます。そして下を実行。最後のyour passwordとしているところは適宜変更してください。

$ sudo mysql
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your password';
mysql> exit

続きの設定をしていきます。

$ sudo mysql_secure_installation
Change the password for root ? ((Press y|Y for Yes, any other key for No) : no
Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
All done!

設定完了したら次のコマンドでログインして、各種操作ができることを確認しましょう。

$ mysql -u root -p

# ユーザを作る場合
mysql> CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
# ユーザにデータベースへのアクセスを許可
mysql> GRANT ALL ON databasename.* TO 'username'@'localhost';
データベース初期化・マイグレーション設定
export FLASK_APP=apps.main.py
export FLASK_ENV=development

flask db init
flask db migrate
起動

単にflask runだとlocalhostにバインドされるので、例えばLAN内の他の機器からアクセスしたければ自身のローカルIPやポートをオプションで指定します。

$ export FLASK_APP=main.py
$ export FLASK_ENV=development
$ flask run -h 192.168.0.xxx -p 5000
(おまけ)トラブルシューティング

flask db migrateで以下のエラーに遭遇した。

sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1045, "Access denied for user 'user'@'localhost' (using password: NO)")

stackoverflowにはいくつか解決方法が提示されていましたが、自分の場合はSQLALCHEMY_DATABASE_URIで指定したURIが誤っていました。

stackoverflow.com