Skip to content
Myr

sqlalchemy.rst

This file

Path

docs/patterns/sqlalchemy.rst

218 lines · 7.2 KiB

Last changed by

Merge pull request #869 from christophersu/doc-fix-1Kenneth Reitzbefore adoption7e4d51c

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        # import all modules here that might define models so that51        # they will be registered properly on the metadata.  Otherwise52        # you will have to import them first before calling init_db()53        import yourapplication.models54        Base.metadata.create_all(bind=engine)5556To define your models, just subclass the `Base` class that was created by57the code above.  If you are wondering why we don't have to care about58threads here (like we did in the SQLite3 example above with the59:data:`~flask.g` object): that's because SQLAlchemy does that for us60already with the :class:`~sqlalchemy.orm.scoped_session`.6162To use SQLAlchemy in a declarative way with your application, you just63have to put the following code into your application module.  Flask will64automatically remove database sessions at the end of the request or65when the application shuts down::6667    from yourapplication.database import db_session6869    @app.teardown_appcontext70    def shutdown_session(exception=None):71        db_session.remove()7273Here is an example model (put this into `models.py`, e.g.)::7475    from sqlalchemy import Column, Integer, String76    from yourapplication.database import Base7778    class User(Base):79        __tablename__ = 'users'80        id = Column(Integer, primary_key=True)81        name = Column(String(50), unique=True)82        email = Column(String(120), unique=True)8384        def __init__(self, name=None, email=None):85            self.name = name86            self.email = email8788        def __repr__(self):89            return '<User %r>' % (self.name)9091To create the database you can use the `init_db` function:9293>>> from yourapplication.database import init_db94>>> init_db()9596You can insert entries into the database like this:9798>>> from yourapplication.database import db_session99>>> from yourapplication.models import User100>>> u = User('admin', 'admin@localhost')101>>> db_session.add(u)102>>> db_session.commit()103104Querying is simple as well:105106>>> User.query.all()107[<User u'admin'>]108>>> User.query.filter(User.name == 'admin').first()109<User u'admin'>110111.. _SQLAlchemy: http://www.sqlalchemy.org/112.. _declarative:113   http://www.sqlalchemy.org/docs/orm/extensions/declarative.html114115Manual Object Relational Mapping116--------------------------------117118Manual object relational mapping has a few upsides and a few downsides119versus the declarative approach from above.  The main difference is that120you define tables and classes separately and map them together.  It's more121flexible but a little more to type.  In general it works like the122declarative approach, so make sure to also split up your application into123multiple modules in a package.124125Here is an example `database.py` module for your application::126127    from sqlalchemy import create_engine, MetaData128    from sqlalchemy.orm import scoped_session, sessionmaker129130    engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)131    metadata = MetaData()132    db_session = scoped_session(sessionmaker(autocommit=False,133                                             autoflush=False,134                                             bind=engine))135    def init_db():136        metadata.create_all(bind=engine)137138As for the declarative approach you need to close the session after139each request or application context shutdown.  Put this into your140application module::141142    from yourapplication.database import db_session143144    @app.teardown_appcontext145    def shutdown_session(exception=None):146        db_session.remove()147148Here is an example table and model (put this into `models.py`)::149150    from sqlalchemy import Table, Column, Integer, String151    from sqlalchemy.orm import mapper152    from yourapplication.database import metadata, db_session153154    class User(object):155        query = db_session.query_property()156157        def __init__(self, name=None, email=None):158            self.name = name159            self.email = email160161        def __repr__(self):162            return '<User %r>' % (self.name)163164    users = Table('users', metadata,165        Column('id', Integer, primary_key=True),166        Column('name', String(50), unique=True),167        Column('email', String(120), unique=True)168    )169    mapper(User, users)170171Querying and inserting works exactly the same as in the example above.172173174SQL Abstraction Layer175---------------------176177If you just want to use the database system (and SQL) abstraction layer178you basically only need the engine::179180    from sqlalchemy import create_engine, MetaData181182    engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)183    metadata = MetaData(bind=engine)184185Then you can either declare the tables in your code like in the examples186above, or automatically load them::187188    from sqlalchemy import Table189    190    users = Table('users', metadata, autoload=True)191192To insert data you can use the `insert` method.  We have to get a193connection first so that we can use a transaction:194195>>> con = engine.connect()196>>> con.execute(users.insert(), name='admin', email='admin@localhost')197198SQLAlchemy will automatically commit for us.199200To query your database, you use the engine directly or use a connection:201202>>> users.select(users.c.id == 1).execute().first()203(1, u'admin', u'admin@localhost')204205These results are also dict-like tuples:206207>>> r = users.select(users.c.id == 1).execute().first()208>>> r['name']209u'admin'210211You can also pass strings of SQL statements to the212:meth:`~sqlalchemy.engine.base.Connection.execute` method:213214>>> engine.execute('select * from users where id = :1', [1]).first()215(1, u'admin', u'admin@localhost')216217For more information about SQLAlchemy, head over to the218`website <http://sqlalchemy.org/>`_.