Skip to content
Myr

sqlalchemy.rst

This file

Path

docs/patterns/sqlalchemy.rst

214 lines · 7.2 KiB

Last changed by

Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18

History of this file

Take it

The walk stopped after 200 commits: lines older than 778e44e point at it.

Improved error message for configuration filesArmin Ronacherbefore adoption778e44e

lines 1–49why, 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,45 bind=engine)) 46 Base = declarative_base()47 Base.query = db_session.query_property()4849 def init_db():

Improved documentation for model registrationArmin Ronacherbefore adoption24c1713

lines 50–53why, one step back
50 # import all modules here that might define models so that
51 # they will be registered properly on the metadata. Otherwise52 # you will have to import them first before calling init_db()53 import yourapplication.models

Improved error message for configuration filesArmin Ronacherbefore adoption778e44e

lines 54–67why, one step back
54 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 for you::6566 from yourapplication.database import db_session67

Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18

lines 68–69why, one step back
68 @app.teardown_request
69 def shutdown_session(exception=None):

Improved error message for configuration filesArmin Ronacherbefore adoption778e44e

lines 70–88why, one step back
70 db_session.remove()
7172Here is an example model (put this into `models.py`, e.g.)::7374 from sqlalchemy import Column, Integer, String75 from yourapplication.database import Base7677 class User(Base):78 __tablename__ = 'users'79 id = Column(Integer, primary_key=True)80 name = Column(String(50), unique=True)81 email = Column(String(120), unique=True)8283 def __init__(self, name=None, email=None):84 self.name = name85 self.email = email8687 def __repr__(self):88 return '<User %r>' % (self.name)

Improved documentation for model registrationArmin Ronacherbefore adoption24c1713

lines 89–93why, one step back
89
90To create the database you can use the `init_db` function:9192>>> from yourapplication.database import init_db93>>> init_db()

Improved error message for configuration filesArmin Ronacherbefore adoption778e44e

lines 94–111why, one step back
94
95You can insert entries into the database like this:9697>>> from yourapplication.database import db_session98>>> from yourapplication.models import User99>>> u = User('admin', 'admin@localhost')100>>> db_session.add(u)101>>> db_session.commit()102103Querying is simple as well:104105>>> User.query.all()106[<User u'admin'>]107>>> User.query.filter(User.name == 'admin').first()108<User u'admin'>109110.. _SQLAlchemy: http://www.sqlalchemy.org/111.. _declarative:

Updated 'declarative' link in docs/patterns/sqlalchemy.rstJerry Bakerbefore adoption09a06ab

line 112why, one step back
112 http://www.sqlalchemy.org/docs/orm/extensions/declarative.html

Improved error message for configuration filesArmin Ronacherbefore adoption778e44e

lines 113–141why, one step back
113
114Manual Object Relational Mapping115--------------------------------116117Manual object relational mapping has a few upsides and a few downsides118versus the declarative approach from above. The main difference is that119you define tables and classes separately and map them together. It's more120flexible but a little more to type. In general it works like the121declarative approach, so make sure to also split up your application into122multiple modules in a package.123124Here is an example `database.py` module for your application::125126 from sqlalchemy import create_engine, MetaData127 from sqlalchemy.orm import scoped_session, sessionmaker128129 engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)130 metadata = MetaData()131 db_session = scoped_session(sessionmaker(autocommit=False,132 autoflush=False,133 bind=engine)) 134 def init_db():135 metadata.create_all(bind=engine)136137As for the declarative approach you need to close the session after138each request. Put this into your application module::139140 from yourapplication.database import db_session141

Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18

lines 142–143why, one step back
142 @app.teardown_request
143 def shutdown_session(exception=None):

Improved error message for configuration filesArmin Ronacherbefore adoption778e44e

lines 144–214why, one step back
144 db_session.remove()
145146Here is an example table and model (put this into `models.py`)::147148 from sqlalchemy import Table, Column, Integer, String149 from sqlalchemy.orm import mapper150 from yourapplication.database import metadata, db_session151152 class User(object):153 query = db_session.query_property()154155 def __init__(self, name=None, email=None):156 self.name = name157 self.email = email158159 def __repr__(self):160 return '<User %r>' % (self.name, self.email)161162 users = Table('users', metadata,163 Column('id', Integer, primary_key=True),164 Column('name', String(50), unique=True),165 Column('email', String(120), unique=True)166 )167 mapper(User, users)168169Querying and inserting works exactly the same as in the example above.170171172SQL Abstraction Layer173---------------------174175If you just want to use the database system (and SQL) abstraction layer176you basically only need the engine::177178 from sqlalchemy import create_engine, MetaData179180 engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)181 metadata = MetaData(bind=engine)182183Then you can either declare the tables in your code like in the examples184above, or automatically load them::185186 users = Table('users', metadata, autoload=True)187188To insert data you can use the `insert` method. We have to get a189connection first so that we can use a transaction:190191>>> con = engine.connect()192>>> con.execute(users.insert(name='admin', email='admin@localhost'))193194SQLAlchemy will automatically commit for us.195196To query your database, you use the engine directly or use a connection:197198>>> users.select(users.c.id == 1).execute().first()199(1, u'admin', u'admin@localhost')200201These results are also dict-like tuples:202203>>> r = users.select(users.c.id == 1).execute().first()204>>> r['name']205u'admin'206207You can also pass strings of SQL statements to the208:meth:`~sqlalchemy.engine.base.Connection.execute` method:209210>>> engine.execute('select * from users where id = :1', [1]).first()211(1, u'admin', u'admin@localhost')212213For more information about SQLAlchemy, head over to the214`website <http://sqlalchemy.org/>`_.