久しぶりに peewee を使うので、復習した際のメモ。ドキュメントに書いてある内容を、忘れないようにメモする目的。随時追加予定。
unique のカラムを指定しなかった場合は、暗黙的に auto_increment の id というカラムが追加される
We have explicitly defined a single username column with a unique constraint. Because we have not specified a primary key, peewee will automatically add an auto-incrementing integer primary key field named id.
ForeignKeyField の被参照側には、小文字クラス名_set のプロパティが暗黙的に追加される
ForeignKeyField の backref で上書き可。
ForeignKeyField allows for a backreferencing property to be bound to the target model. Implicitly, this property will be named classname_set, where classname is the lowercase name of the class, but can be overridden via the parameter backref
なお、被参照側のオブジェクトを取得する前に、ForeignKeyField を使っているモジュールをインポートしておかないと、backreferencing property は、被参照側のオブジェクトに追加されないので注意が必要。30 分ほど悩んだ。
SQLite 以外のデータベースを使う時は、追加でライブラリのインストールが必要
To use Peewee, you typically won’t need anything outside the standard library, since most Python distributions are compiled with SQLite support. You can test by running import sqlite3 in the Python console. If you wish to use another database, there are many DB-API 2.0-compatible drivers out there, such as pymysql or psycopg2 for MySQL and Postgres respectively.
peewee と直接関係ないが、Python で MySQL につなぐ場合、ライブラリがたくさんあって、どれを使えば良いか分かりにくい。
とりあえず、この stackoverflow を読んで、MySQL オフィシャルの mysql-connector-python を使うことにする。
上の stackoverflow によると、他は C のラッパーになってる mysqlclient、Pure Python で作られてる PyMySQL がメジャーみたい。
ただ、peewee では、mysql-connector-python は、サポートしていないっぽい。
try:
import MySQLdb as mysql # prefer the C module.
except ImportError:
try:
import pymysql as mysql
except ImportError:
mysql = None
とりあえず、めんどくさくなったので、インストールが簡単そうな PyMySQL を使いつつ、peewee に質問することにする。
https://github.com/coleifer/peewee/issues/1501
peewee レポジトリのオーナーの方が返答をくれました。
I'm not familiar with mysql-connector-python, but Peewee should work with any DB-API 2.0-compatible driver. If the mysql-connector-python library is fully DB-API 2.0 compatible, you should be able to simply subclass MySQLDatabase and override the _connect() method so it uses the mysql connector.
You can refer to this document for more information: http://docs.peewee-orm.com/en/latest/peewee/database.html#adding-a-new-database-driver
DB-API 2.0-compatible driver であれば使えるはずなので、MySQLDatabase のサブクラスを作って使ってみてねとのこと。
DB とのコネクションがタイムアウトとかで切れちゃう心配がある時は、Connection クラスの ping を呼ぶ
この stackoverflow にて学ぶ。
where for the ping function there is:
Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted.
peewee のバージョンが上がって変わったのか、Connection クラスのインスタンスは、ドライバーの connection メソッドから取れる。