Skip to content
Myr

sqlalchemy.rst

This file

Path

docs/patterns/sqlalchemy.rst

193 lines · 6.3 KiB

Last changed by

Proofreading the documentationChris Edgemonbefore adoptiona7ff9db

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 three very common ways to use SQLAlchemy.  I will outline each12of them here:1314Declarative15-----------1617The declarative extension in SQLAlchemy is the most recent method of using18SQLAlchemy.  It allows you to define tables and models in one go, similar19to how Django works.  In addition to the following text I recommend the20official documentation on the `declarative`_ extension.2122Here the example `database.py` module for your application::2324    from sqlalchemy import create_engine25    from sqlalchemy.orm import scoped_session, sessionmaker26    from sqlalchemy.ext.declarative import declarative_base2728    engine = create_engine('sqlite:////tmp/test.db')29    db_session = scoped_session(sessionmaker(autocommit=False,30                                             autoflush=False,31                                             bind=engine)) 32    Base = declarative_base()33    Base.query = db_session.query_property()3435    def init_db():36        Base.metadata.create_all(bind=engine)3738To define your models, just subclass the `Base` class that was created by39the code above.  If you are wondering why we don't have to care about40threads here (like we did in the SQLite3 example above with the41:data:`~flask.g` object): that's because SQLAlchemy does that for us42already with the :class:`~sqlalchemy.orm.scoped_session`.4344To use SQLAlchemy in a declarative way with your application, you just45have to put the following code into your application module.  Flask will46automatically remove database sessions at the end of the request for you::4748    from yourapplication.database import db_session4950    @app.after_request51    def shutdown_session(response):52        db_session.remove()53        return response5455Here is an example model (put this into `models.py`, e.g.)::5657    from sqlalchemy import Column, Integer, String58    from yourapplication.database import Base5960    class User(Base):61        __tablename__ = 'users'62        id = Column(Integer, primary_key=True)63        name = Column(String(50), unique=True)64        email = Column(String(120), unique=True)6566        def __init__(self, name=None, email=None):67            self.name = name68            self.email = email6970        def __repr__(self):71            return '<User %r>' % (self.name, self.email)7273You can insert entries into the database like this:7475>>> from yourapplication.database import db_session76>>> from yourapplication.models import User77>>> u = User('admin', 'admin@localhost')78>>> db_session.add(u)79>>> db_session.commit()8081Querying is simple as well:8283>>> User.query.all()84[<User u'admin'>]85>>> User.query.filter(User.name == 'admin').first()86<User u'admin'>8788.. _SQLAlchemy: http://www.sqlalchemy.org/89.. _declarative:90   http://www.sqlalchemy.org/docs/reference/ext/declarative.html9192Manual Object Relational Mapping93--------------------------------9495Manual object relational mapping has a few upsides and a few downsides96versus the declarative approach from above.  The main difference is that97you define tables and classes separately and map them together.  It's more98flexible but a little more to type.  In general it works like the99declarative approach, so make sure to also split up your application into100multiple modules in a package.101102Here is an example `database.py` module for your application::103104    from sqlalchemy import create_engine, MetaData105    from sqlalchemy.orm import scoped_session, sessionmaker106107    engine = create_engine('sqlite:////tmp/test.db')108    metadata = MetaData()109    db_session = scoped_session(sessionmaker(autocommit=False,110                                             autoflush=False,111                                             bind=engine)) 112    def init_db():113        metadata.create_all(bind=engine)114115As for the declarative approach you need to close the session after116each request.  Put this into your application module::117118    from yourapplication.database import db_session119120    @app.after_request121    def shutdown_session(response):122        db_session.remove()123        return response124125Here is an example table and model (put this into `models.py`)::126127    from sqlalchemy import Table, Column, Integer, String128    from sqlalchemy.orm import mapper129    from yourapplication.database import metadata, db_session130131    class User(object):132        query = db_session.query_property()133134        def __init__(self, name=None, email=None):135            self.name = name136            self.email = email137138        def __repr__(self):139            return '<User %r>' % (self.name, self.email)140141    users = Table('users', metadata,142        Column('id', Integer, primary_key=True),143        Column('name', String(50), unique=True),144        Column('email', String(120), unique=True)145    )146    mapper(User, users)147148Querying and inserting works exactly the same as in the example above.149150151SQL Abstraction Layer152---------------------153154If you just want to use the database system (and SQL) abstraction layer155you basically only need the engine::156157    from sqlalchemy import create_engine, MetaData158159    engine = create_engine('sqlite:////tmp/test.db')160    metadata = MetaData(bind=engine)161162Then you can either declare the tables in your code like in the examples163above, or automatically load them::164165    users = Table('users', metadata, autoload=True)166167To insert data you can use the `insert` method.  We have to get a168connection first so that we can use a transaction:169170>>> con = engine.connect()171>>> con.execute(users.insert(name='admin', email='admin@localhost'))172173SQLAlchemy will automatically commit for us.174175To query your database, you use the engine directly or use a connection:176177>>> users.select(users.c.id == 1).execute().first()178(1, u'admin', u'admin@localhost')179180These results are also dict-like tuples:181182>>> r = users.select(users.c.id == 1).execute().first()183>>> r['name']184u'admin'185186You can also pass strings of SQL statements to the187:meth:`~sqlalchemy.engine.base.Connection.execute` method:188189>>> engine.execute('select * from users where id = :1', [1]).first()190(1, u'admin', u'admin@localhost')191192For more information about SQLAlchemy, head over to the193`website <http://sqlalchemy.org/>`_.