Flask内でのSQLAlchemy(SQLAlchemy in Flask) SQLAlchemy in Flask

多くの人がデータベースへのアクセスにSQLAlchemyを好みます。以下の例ではflaskアプリケーションでモジュールの代わりにパッケージを使用し、(データベースの)モデルを(アプリケーションとは)別のモジュールに落とし込む(パッケージにした大きなアプリケーション(Large Applications as Packages))ことを推奨しています。それは必須ではありませんが、とても理にかなっています。 Many people prefer `SQLAlchemy`_ for database access. In this case it's encouraged to use a package instead of a module for your flask application and drop the models into a separate module (:doc:`packages`). While that is not necessary, it makes a lot of sense.

SQLAlchemyの使い方には4つのよくあるやり方があります。それぞれの概要を以下に示します: There are four very common ways to use SQLAlchemy. I will outline each of them here:

Flask-SQLAlchemy拡張 Flask-SQLAlchemy Extension

SQLAlchemyは一般的なデータベース抽象化階層で要する手間が少しの設定のオブジェクト・リレーショナル・マッパーであるため、SQLAlchemyを扱うFlask拡張が存在します。手っ取り早く始めたいときはお勧めです。 Because SQLAlchemy is a common database abstraction layer and object relational mapper that requires a little bit of configuration effort, there is a Flask extension that handles that for you. This is recommended if you want to get started quickly.

Flask-SQLAlchemyPyPIからダウンロードできます。 You can download `Flask-SQLAlchemy`_ from `PyPI <https://pypi.org/project/Flask-SQLAlchemy/>`_.

宣言的(Declarative) Declarative

SQLAlchemyの宣言的(な使用方法)の拡張はSQLAlchemyを使用するもっとも新しい手法です。それはDjangoのやり方と似たように、一緒にテーブルとモデルを定義できます。以下の文に加えて、declarative拡張についての公式のドキュメントをお勧めします。 The declarative extension in SQLAlchemy is the most recent method of using SQLAlchemy. It allows you to define tables and models in one go, similar to how Django works. In addition to the following text I recommend the official documentation on the `declarative`_ extension.

以下はアプリケーション用のdatabase.pyモジュールの例です: Here's the example :file:`database.py` module for your application::

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:////tmp/test.db')
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    import yourapplication.models
    Base.metadata.create_all(bind=engine)

自分のモデルを定義するには、先のコードで作成されたBaseクラスをただサブクラス化します。ここで(gオブジェクトを使ったSQLite3の先の例ではしたような)スレッドへの注意を払わないことを不思議に思う場合: それはSQLAlchemyがscoped_sessionを使って既に対応してくれているためです。 To define your models, just subclass the `Base` class that was created by the code above. If you are wondering why we don't have to care about threads here (like we did in the SQLite3 example above with the :data:`~flask.g` object): that's because SQLAlchemy does that for us already with the :class:`~sqlalchemy.orm.scoped_session`.

アプリケーションでSQLAlchemyを宣言的なやり方で使うには、以下のコードを自分のアプリケーションのモジュールに置く必要があるだけです。Flaskは、リクエストの最後またはアプリケーションの終了時に、自動的にデータベースのセッションを取り除きます: To use SQLAlchemy in a declarative way with your application, you just have to put the following code into your application module. Flask will automatically remove database sessions at the end of the request or when the application shuts down::

from yourapplication.database import db_session

@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()

以下はモデルの例です(例えばこれをmodels.py内に置きます): Here is an example model (put this into :file:`models.py`, e.g.)::

from sqlalchemy import Column, Integer, String
from yourapplication.database import Base

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True)
    email = Column(String(120), unique=True)

    def __init__(self, name=None, email=None):
        self.name = name
        self.email = email

    def __repr__(self):
        return f'<User {self.name!r}>'

データベースを作成するにはinit_db関数を使用できます: To create the database you can use the `init_db` function:

>>> from yourapplication.database import init_db
>>> init_db()

以下のようにしてデータベースへエントリーを挿入できます: You can insert entries into the database like this:

>>> from yourapplication.database import db_session
>>> from yourapplication.models import User
>>> u = User('admin', 'admin@localhost')
>>> db_session.add(u)
>>> db_session.commit()

問合せ(query)も同様にシンプルです: Querying is simple as well:

>>> User.query.all()
[<User 'admin'>]
>>> User.query.filter(User.name == 'admin').first()
<User 'admin'>

手作業でのオブジェクト・リレーショナル・マッピング Manual Object Relational Mapping

手作業でのオブジェクト・リレーショナル・マッピングは、上述の宣言的アプローチに対していくつかの利点と欠点があります。主な違いは、テーブルとクラスを分けて定義しそれらを対応付けることです。それはより柔軟ですが、少しタイプ量が多くなります。概して、宣言的アプローチと同じように働くため、アプリケーションをパッケージの中で複数のモジュールに分割することを確実に行ってください。 Manual object relational mapping has a few upsides and a few downsides versus the declarative approach from above. The main difference is that you define tables and classes separately and map them together. It's more flexible but a little more to type. In general it works like the declarative approach, so make sure to also split up your application into multiple modules in a package.

以下はアプリケーション用のdatabase.pyモジュールの例です: Here is an example :file:`database.py` module for your application::

from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine('sqlite:////tmp/test.db')
metadata = MetaData()
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
def init_db():
    metadata.create_all(bind=engine)

宣言的アプローチの中と同様、各リクエストまたはアプリケーションのコンテキストの終了後はセッションを閉じる必要があります。以下を自分のアプリケーションのモジュールに置いてください: As in the declarative approach, you need to close the session after each request or application context shutdown. Put this into your application module::

from yourapplication.database import db_session

@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()

以下はテーブルとモデルの例です(これをmodels.pyに置きます): Here is an example table and model (put this into :file:`models.py`)::

from sqlalchemy import Table, Column, Integer, String
from sqlalchemy.orm import mapper
from yourapplication.database import metadata, db_session

class User(object):
    query = db_session.query_property()

    def __init__(self, name=None, email=None):
        self.name = name
        self.email = email

    def __repr__(self):
        return f'<User {self.name!r}>'

users = Table('users', metadata,
    Column('id', Integer, primary_key=True),
    Column('name', String(50), unique=True),
    Column('email', String(120), unique=True)
)
mapper(User, users)

問合せ(query)と挿入は先の例とまったく同様に働きます。 Querying and inserting works exactly the same as in the example above.

SQL抽象化階層 SQL Abstraction Layer

もしデータベースシステム(とSQL)の抽象化階層を使いたいだけの場合、必要なものは基本的にエンジンだけです: If you just want to use the database system (and SQL) abstraction layer you basically only need the engine::

from sqlalchemy import create_engine, MetaData, Table

engine = create_engine('sqlite:////tmp/test.db')
metadata = MetaData(bind=engine)

それから先の例のように自分のコードの中でテーブルを宣言するか、またはテーブルを自動的にロードできます: Then you can either declare the tables in your code like in the examples above, or automatically load them::

from sqlalchemy import Table

users = Table('users', metadata, autoload=True)

データを挿入するにはinsertメソッドを使用できます。トランザクションを使用できるようにするため、最初に接続(connection)を取得します: To insert data you can use the `insert` method. We have to get a connection first so that we can use a transaction:

>>> con = engine.connect()
>>> con.execute(users.insert(), name='admin', email='admin@localhost')

SQLAlchemyは自動的にコミットします。 SQLAlchemy will automatically commit for us.

データベースに問合せ(query)するには、直接エンジンを使うかconnectionを使います: To query your database, you use the engine directly or use a connection:

>>> users.select(users.c.id == 1).execute().first()
(1, 'admin', 'admin@localhost')

これらの結果もdictのようなtupleになります: These results are also dict-like tuples:

>>> r = users.select(users.c.id == 1).execute().first()
>>> r['name']
'admin'

execute()メソッドへSQL文の文字列を渡すこともできます: You can also pass strings of SQL statements to the :meth:`~sqlalchemy.engine.base.Connection.execute` method:

>>> engine.execute('select * from users where id = :1', [1]).first()
(1, 'admin', 'admin@localhost')

SQLAlchemyに関するさらなる情報は、webサイトを調べてください。 For more information about SQLAlchemy, head over to the `website <https://www.sqlalchemy.org/>`_.