SQLAlchemy in Flask

Many people prefer SQLAlchemy for database access. In this case it’sencouraged to use a package instead of a module for your flask applicationand drop the models into a separate module (Larger Applications).While that is not necessary, it makes a lot of sense.

There are four very common ways to use SQLAlchemy. I will outline eachof them here:

Flask-SQLAlchemy Extension

Because SQLAlchemy is a common database abstraction layer and objectrelational mapper that requires a little bit of configuration effort,there is a Flask extension that handles that for you. This is recommendedif you want to get started quickly.

You can download Flask-SQLAlchemy from PyPI.

Declarative

The declarative extension in SQLAlchemy is the most recent method of usingSQLAlchemy. It allows you to define tables and models in one go, similarto how Django works. In addition to the following text I recommend theofficial documentation on the declarative extension.

Here’s the example database.py module for your application:

  1. from sqlalchemy import create_engine
  2. from sqlalchemy.orm import scoped_session, sessionmaker
  3. from sqlalchemy.ext.declarative import declarative_base
  4.  
  5. engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)
  6. db_session = scoped_session(sessionmaker(autocommit=False,
  7. autoflush=False,
  8. bind=engine))
  9. Base = declarative_base()
  10. Base.query = db_session.query_property()
  11.  
  12. def init_db():
  13. # import all modules here that might define models so that
  14. # they will be registered properly on the metadata. Otherwise
  15. # you will have to import them first before calling init_db()
  16. import yourapplication.models
  17. Base.metadata.create_all(bind=engine)

To define your models, just subclass the Base class that was created bythe code above. If you are wondering why we don’t have to care aboutthreads here (like we did in the SQLite3 example above with theg object): that’s because SQLAlchemy does that for usalready with the scoped_session.

To use SQLAlchemy in a declarative way with your application, you justhave to put the following code into your application module. Flask willautomatically remove database sessions at the end of the request orwhen the application shuts down:

  1. from yourapplication.database import db_session
  2.  
  3. @app.teardown_appcontext
  4. def shutdown_session(exception=None):
  5. db_session.remove()

Here is an example model (put this into models.py, e.g.):

  1. from sqlalchemy import Column, Integer, String
  2. from yourapplication.database import Base
  3.  
  4. class User(Base):
  5. __tablename__ = 'users'
  6. id = Column(Integer, primary_key=True)
  7. name = Column(String(50), unique=True)
  8. email = Column(String(120), unique=True)
  9.  
  10. def __init__(self, name=None, email=None):
  11. self.name = name
  12. self.email = email
  13.  
  14. def __repr__(self):
  15. return '<User %r>' % (self.name)

To create the database you can use the init_db function:

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

You can insert entries into the database like this:

  1. >>> from yourapplication.database import db_session
  2. >>> from yourapplication.models import User
  3. >>> u = User('admin', '[email protected]')
  4. >>> db_session.add(u)
  5. >>> db_session.commit()

Querying is simple as well:

  1. >>> User.query.all()
  2. [<User u'admin'>]
  3. >>> User.query.filter(User.name == 'admin').first()
  4. <User u'admin'>

Manual Object Relational Mapping

Manual object relational mapping has a few upsides and a few downsidesversus the declarative approach from above. The main difference is thatyou define tables and classes separately and map them together. It’s moreflexible but a little more to type. In general it works like thedeclarative approach, so make sure to also split up your application intomultiple modules in a package.

Here is an example database.py module for your application:

  1. from sqlalchemy import create_engine, MetaData
  2. from sqlalchemy.orm import scoped_session, sessionmaker
  3.  
  4. engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)
  5. metadata = MetaData()
  6. db_session = scoped_session(sessionmaker(autocommit=False,
  7. autoflush=False,
  8. bind=engine))
  9. def init_db():
  10. metadata.create_all(bind=engine)

As in the declarative approach, you need to close the session aftereach request or application context shutdown. Put this into yourapplication module:

  1. from yourapplication.database import db_session
  2.  
  3. @app.teardown_appcontext
  4. def shutdown_session(exception=None):
  5. db_session.remove()

Here is an example table and model (put this into models.py):

  1. from sqlalchemy import Table, Column, Integer, String
  2. from sqlalchemy.orm import mapper
  3. from yourapplication.database import metadata, db_session
  4.  
  5. class User(object):
  6. query = db_session.query_property()
  7.  
  8. def __init__(self, name=None, email=None):
  9. self.name = name
  10. self.email = email
  11.  
  12. def __repr__(self):
  13. return '<User %r>' % (self.name)
  14.  
  15. users = Table('users', metadata,
  16. Column('id', Integer, primary_key=True),
  17. Column('name', String(50), unique=True),
  18. Column('email', String(120), unique=True)
  19. )
  20. mapper(User, users)

Querying and inserting works exactly the same as in the example above.

SQL Abstraction Layer

If you just want to use the database system (and SQL) abstraction layeryou basically only need the engine:

  1. from sqlalchemy import create_engine, MetaData, Table
  2.  
  3. engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)
  4. metadata = MetaData(bind=engine)

Then you can either declare the tables in your code like in the examplesabove, or automatically load them:

  1. from sqlalchemy import Table
  2.  
  3. users = Table('users', metadata, autoload=True)

To insert data you can use the insert method. We have to get aconnection first so that we can use a transaction:

  1. >>> con = engine.connect()
  2. >>> con.execute(users.insert(), name='admin', email='[email protected]')

SQLAlchemy will automatically commit for us.

To query your database, you use the engine directly or use a connection:

  1. >>> users.select(users.c.id == 1).execute().first()
  2. (1, u'admin', u'[email protected]')

These results are also dict-like tuples:

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

You can also pass strings of SQL statements to theexecute() method:

  1. >>> engine.execute('select * from users where id = :1', [1]).first()
  2. (1, u'admin', u'[email protected]')

For more information about SQLAlchemy, head over to thewebsite.