Skip to content
Myr

sqlalchemy.rst

This file

Path

docs/patterns/sqlalchemy.rst

216 lines · 7.2 KiB

Last changed by

Switch to teardown_appcontext for docs in sqlalchemy patternArmin Ronacherbefore adoption681cb8f

History of this file

Take it

The walk stopped after 200 commits: lines older than 22af78a point at it.

Removed outdated sentence in the testing docsArmin Ronacherbefore adoption22af78a

lines 1–44why, one step back
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,

Merge pull request #590 from pinchsp/masterArmin Ronacherbefore adoptionb2cf9e7

line 45why, one step back
45 bind=engine))

Removed outdated sentence in the testing docsArmin Ronacherbefore adoption22af78a

lines 46–63why, one step back
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 will

Switch to teardown_appcontext for docs in sqlalchemy patternArmin Ronacherbefore adoption681cb8f

lines 64–65why, one step back
64automatically remove database sessions at the end of the request or
65when the application shuts down::

Removed outdated sentence in the testing docsArmin Ronacherbefore adoption22af78a

lines 66–68why, one step back
66
67 from yourapplication.database import db_session68

Switch to teardown_appcontext for docs in sqlalchemy patternArmin Ronacherbefore adoption681cb8f

line 69why, one step back
69 @app.teardown_appcontext

Removed outdated sentence in the testing docsArmin Ronacherbefore adoption22af78a

lines 70–133why, one step back
70 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,

Merge pull request #590 from pinchsp/masterArmin Ronacherbefore adoptionb2cf9e7

line 134why, one step back
134 bind=engine))

Removed outdated sentence in the testing docsArmin Ronacherbefore adoption22af78a

lines 135–138why, one step back
135 def init_db():
136 metadata.create_all(bind=engine)137138As for the declarative approach you need to close the session after

Switch to teardown_appcontext for docs in sqlalchemy patternArmin Ronacherbefore adoption681cb8f

lines 139–140why, one step back
139each request or application context shutdown. Put this into your
140application module::

Removed outdated sentence in the testing docsArmin Ronacherbefore adoption22af78a

lines 141–143why, one step back
141
142 from yourapplication.database import db_session143

Switch to teardown_appcontext for docs in sqlalchemy patternArmin Ronacherbefore adoption681cb8f

line 144why, one step back
144 @app.teardown_appcontext

Removed outdated sentence in the testing docsArmin Ronacherbefore adoption22af78a

lines 145–193why, one step back
145 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 users = Table('users', metadata, autoload=True)189190To insert data you can use the `insert` method. We have to get a191connection first so that we can use a transaction:192193>>> con = engine.connect()

Merge pull request #590 from pinchsp/masterArmin Ronacherbefore adoptionb2cf9e7

line 194why, one step back
194>>> con.execute(users.insert(), name='admin', email='admin@localhost')

Removed outdated sentence in the testing docsArmin Ronacherbefore adoption22af78a

lines 195–216why, one step back
195
196SQLAlchemy will automatically commit for us.197198To query your database, you use the engine directly or use a connection:199200>>> users.select(users.c.id == 1).execute().first()201(1, u'admin', u'admin@localhost')202203These results are also dict-like tuples:204205>>> r = users.select(users.c.id == 1).execute().first()206>>> r['name']207u'admin'208209You can also pass strings of SQL statements to the210:meth:`~sqlalchemy.engine.base.Connection.execute` method:211212>>> engine.execute('select * from users where id = :1', [1]).first()213(1, u'admin', u'admin@localhost')214215For more information about SQLAlchemy, head over to the216`website <http://sqlalchemy.org/>`_.