Skip to content
Myr

sqlalchemy.rst

This file

Path

docs/patterns/sqlalchemy.rst

207 lines · 6.8 KiB

Last changed by

Added links to Flask-WTF and Flask-SQLAlchemy. This fixes #73Armin Ronacherbefore adoptiond0357b4

History of this file

Take it

1.. _sqlalchemy-pattern:23SQLAlchemy in Flask4===================56Many people prefer `SQLAlchemy`_ for database access.  In this case it's7encouraged to use a package instead of a module for your flask application8and drop the models into a separate module (:ref:`larger-applications`).9While that is not necessary, it makes a lot of sense.1011There are four very common ways to use SQLAlchemy.  I will outline each12of them here:1314Flask-SQLAlchemy Extension15--------------------------1617Because SQLAlchemy is a common database abstraction layer and object18relational mapper that requires a little bit of configuration effort,19there is a Flask extension that handles that for you.  This is recommended20if you want to get started quickly.2122You can download `Flask-SQLAlchemy`_ from `PyPI23<http://pypi.python.org/pypi/Flask-SQLAlchemy>`_.2425.. _Flask-SQLAlchemy: http://packages.python.org/Flask-SQLAlchemy/262728Declarative29-----------3031The declarative extension in SQLAlchemy is the most recent method of using32SQLAlchemy.  It allows you to define tables and models in one go, similar33to how Django works.  In addition to the following text I recommend the34official documentation on the `declarative`_ extension.3536Here the example `database.py` module for your application::3738    from sqlalchemy import create_engine39    from sqlalchemy.orm import scoped_session, sessionmaker40    from sqlalchemy.ext.declarative import declarative_base4142    engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)43    db_session = scoped_session(sessionmaker(autocommit=False,44                                             autoflush=False,45                                             bind=engine)) 46    Base = declarative_base()47    Base.query = db_session.query_property()4849    def init_db():50        Base.metadata.create_all(bind=engine)5152To define your models, just subclass the `Base` class that was created by53the code above.  If you are wondering why we don't have to care about54threads here (like we did in the SQLite3 example above with the55:data:`~flask.g` object): that's because SQLAlchemy does that for us56already with the :class:`~sqlalchemy.orm.scoped_session`.5758To use SQLAlchemy in a declarative way with your application, you just59have to put the following code into your application module.  Flask will60automatically remove database sessions at the end of the request for you::6162    from yourapplication.database import db_session6364    @app.after_request65    def shutdown_session(response):66        db_session.remove()67        return response6869Here is an example model (put this into `models.py`, e.g.)::7071    from sqlalchemy import Column, Integer, String72    from yourapplication.database import Base7374    class User(Base):75        __tablename__ = 'users'76        id = Column(Integer, primary_key=True)77        name = Column(String(50), unique=True)78        email = Column(String(120), unique=True)7980        def __init__(self, name=None, email=None):81            self.name = name82            self.email = email8384        def __repr__(self):85            return '<User %r>' % (self.name)8687You can insert entries into the database like this:8889>>> from yourapplication.database import db_session90>>> from yourapplication.models import User91>>> u = User('admin', 'admin@localhost')92>>> db_session.add(u)93>>> db_session.commit()9495Querying is simple as well:9697>>> User.query.all()98[<User u'admin'>]99>>> User.query.filter(User.name == 'admin').first()100<User u'admin'>101102.. _SQLAlchemy: http://www.sqlalchemy.org/103.. _declarative:104   http://www.sqlalchemy.org/docs/reference/ext/declarative.html105106Manual Object Relational Mapping107--------------------------------108109Manual object relational mapping has a few upsides and a few downsides110versus the declarative approach from above.  The main difference is that111you define tables and classes separately and map them together.  It's more112flexible but a little more to type.  In general it works like the113declarative approach, so make sure to also split up your application into114multiple modules in a package.115116Here is an example `database.py` module for your application::117118    from sqlalchemy import create_engine, MetaData119    from sqlalchemy.orm import scoped_session, sessionmaker120121    engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)122    metadata = MetaData()123    db_session = scoped_session(sessionmaker(autocommit=False,124                                             autoflush=False,125                                             bind=engine)) 126    def init_db():127        metadata.create_all(bind=engine)128129As for the declarative approach you need to close the session after130each request.  Put this into your application module::131132    from yourapplication.database import db_session133134    @app.after_request135    def shutdown_session(response):136        db_session.remove()137        return response138139Here is an example table and model (put this into `models.py`)::140141    from sqlalchemy import Table, Column, Integer, String142    from sqlalchemy.orm import mapper143    from yourapplication.database import metadata, db_session144145    class User(object):146        query = db_session.query_property()147148        def __init__(self, name=None, email=None):149            self.name = name150            self.email = email151152        def __repr__(self):153            return '<User %r>' % (self.name, self.email)154155    users = Table('users', metadata,156        Column('id', Integer, primary_key=True),157        Column('name', String(50), unique=True),158        Column('email', String(120), unique=True)159    )160    mapper(User, users)161162Querying and inserting works exactly the same as in the example above.163164165SQL Abstraction Layer166---------------------167168If you just want to use the database system (and SQL) abstraction layer169you basically only need the engine::170171    from sqlalchemy import create_engine, MetaData172173    engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)174    metadata = MetaData(bind=engine)175176Then you can either declare the tables in your code like in the examples177above, or automatically load them::178179    users = Table('users', metadata, autoload=True)180181To insert data you can use the `insert` method.  We have to get a182connection first so that we can use a transaction:183184>>> con = engine.connect()185>>> con.execute(users.insert(name='admin', email='admin@localhost'))186187SQLAlchemy will automatically commit for us.188189To query your database, you use the engine directly or use a connection:190191>>> users.select(users.c.id == 1).execute().first()192(1, u'admin', u'admin@localhost')193194These results are also dict-like tuples:195196>>> r = users.select(users.c.id == 1).execute().first()197>>> r['name']198u'admin'199200You can also pass strings of SQL statements to the201:meth:`~sqlalchemy.engine.base.Connection.execute` method:202203>>> engine.execute('select * from users where id = :1', [1]).first()204(1, u'admin', u'admin@localhost')205206For more information about SQLAlchemy, head over to the207`website <http://sqlalchemy.org/>`_.