sqlalchemy.rst
This file
Path
docs/patterns/sqlalchemy.rst
207 lines · 6.8 KiB
Last changed by
Added links to Flask-WTF and Flask-SQLAlchemy. This fixes #73Armin Ronacherbefore adoptiond0357b4
History of this fileTake it
The walk stopped after 200 commits: lines older than 8489994 point at it.
Corrected order of the tutorialArmin Ronacherbefore adoption8489994
lines 1–8why, one step back1.. _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`).Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 9why, one step back9While that is not necessary, it makes a lot of sense.Corrected order of the tutorialArmin Ronacherbefore adoption8489994
line 10why, one step back10Added links to Flask-WTF and Flask-SQLAlchemy. This fixes #73Armin Ronacherbefore adoptiond0357b4
line 11why, one step back11There are four very common ways to use SQLAlchemy. I will outline eachCorrected order of the tutorialArmin Ronacherbefore adoption8489994
line 12why, one step back12of them here:Added links to Flask-WTF and Flask-SQLAlchemy. This fixes #73Armin Ronacherbefore adoptiond0357b4
lines 13–26why, one step back1314Flask-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/26Corrected order of the tutorialArmin Ronacherbefore adoption8489994
lines 27–41why, one step back2728Declarative29-----------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_base41Merge branch 'master' into module-supportArmin Ronacherbefore adoption9da5795
line 42why, one step back42 engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)Corrected order of the tutorialArmin Ronacherbefore adoption8489994
lines 43–68why, one step back43 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 Base.metadata.create_all(bind=engine)5152To define your models, just subclass the `Base` class that was created by53the code above. If you are wondering why we don't have to care about54threads here (like we did in the SQLite3 example above with the55:data:`~flask.g` object): that's because SQLAlchemy does that for us56already with the :class:`~sqlalchemy.orm.scoped_session`.5758To use SQLAlchemy in a declarative way with your application, you just59have to put the following code into your application module. Flask will60automatically remove database sessions at the end of the request for you::6162 from yourapplication.database import db_session6364 @app.after_request65 def shutdown_session(response):66 db_session.remove()67 return response68Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 69why, one step back69Here is an example model (put this into `models.py`, e.g.)::Corrected order of the tutorialArmin Ronacherbefore adoption8489994
lines 70–84why, one step back7071 from sqlalchemy import Column, Integer, String72 from yourapplication.database import Base7374 class User(Base):75 __tablename__ = 'users'76 id = Column(Integer, primary_key=True)77 name = Column(String(50), unique=True)78 email = Column(String(120), unique=True)7980 def __init__(self, name=None, email=None):81 self.name = name82 self.email = email8384 def __repr__(self):now really pushed the fix in sqlalchemy patternChristopher Grebsbefore adoptionb5db6bf
line 85why, one step back85 return '<User %r>' % (self.name)Corrected order of the tutorialArmin Ronacherbefore adoption8489994
line 86why, one step back86Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 87why, one step back87You can insert entries into the database like this:Corrected order of the tutorialArmin Ronacherbefore adoption8489994
lines 88–111why, one step back8889>>> from yourapplication.database import db_session90>>> from yourapplication.models import User91>>> u = User('admin', 'admin@localhost')92>>> db_session.add(u)93>>> db_session.commit()9495Querying is simple as well:9697>>> User.query.all()98[<User u'admin'>]99>>> User.query.filter(User.name == 'admin').first()100<User u'admin'>101102.. _SQLAlchemy: http://www.sqlalchemy.org/103.. _declarative:104 http://www.sqlalchemy.org/docs/reference/ext/declarative.html105106Manual Object Relational Mapping107--------------------------------108109Manual object relational mapping has a few upsides and a few downsides110versus the declarative approach from above. The main difference is that111you define tables and classes separately and map them together. It's moreProofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 112why, one step back112flexible but a little more to type. In general it works like theCorrected order of the tutorialArmin Ronacherbefore adoption8489994
lines 113–115why, one step back113declarative approach, so make sure to also split up your application into114multiple modules in a package.115Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 116why, one step back116Here is an example `database.py` module for your application::Corrected order of the tutorialArmin Ronacherbefore adoption8489994
lines 117–120why, one step back117118 from sqlalchemy import create_engine, MetaData119 from sqlalchemy.orm import scoped_session, sessionmaker120Merge branch 'master' into module-supportArmin Ronacherbefore adoption9da5795
line 121why, one step back121 engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)Corrected order of the tutorialArmin Ronacherbefore adoption8489994
lines 122–128why, one step back122 metadata = MetaData()123 db_session = scoped_session(sessionmaker(autocommit=False,124 autoflush=False,125 bind=engine)) 126 def init_db():127 metadata.create_all(bind=engine)128Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 129why, one step back129As for the declarative approach you need to close the session afterCorrected order of the tutorialArmin Ronacherbefore adoption8489994
lines 130–138why, one step back130each request. Put this into your application module::131132 from yourapplication.database import db_session133134 @app.after_request135 def shutdown_session(response):136 db_session.remove()137 return response138Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 139why, one step back139Here is an example table and model (put this into `models.py`)::Corrected order of the tutorialArmin Ronacherbefore adoption8489994
lines 140–172why, one step back140141 from sqlalchemy import Table, Column, Integer, String142 from sqlalchemy.orm import mapper143 from yourapplication.database import metadata, db_session144145 class User(object):146 query = db_session.query_property()147148 def __init__(self, name=None, email=None):149 self.name = name150 self.email = email151152 def __repr__(self):153 return '<User %r>' % (self.name, self.email)154155 users = Table('users', metadata,156 Column('id', Integer, primary_key=True),157 Column('name', String(50), unique=True),158 Column('email', String(120), unique=True)159 )160 mapper(User, users)161162Querying and inserting works exactly the same as in the example above.163164165SQL Abstraction Layer166---------------------167168If you just want to use the database system (and SQL) abstraction layer169you basically only need the engine::170171 from sqlalchemy import create_engine, MetaData172Merge branch 'master' into module-supportArmin Ronacherbefore adoption9da5795
line 173why, one step back173 engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)Corrected order of the tutorialArmin Ronacherbefore adoption8489994
lines 174–188why, one step back174 metadata = MetaData(bind=engine)175176Then you can either declare the tables in your code like in the examples177above, or automatically load them::178179 users = Table('users', metadata, autoload=True)180181To insert data you can use the `insert` method. We have to get a182connection first so that we can use a transaction:183184>>> con = engine.connect()185>>> con.execute(users.insert(name='admin', email='admin@localhost'))186187SQLAlchemy will automatically commit for us.188Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 189why, one step back189To query your database, you use the engine directly or use a connection:Corrected order of the tutorialArmin Ronacherbefore adoption8489994
lines 190–199why, one step back190191>>> users.select(users.c.id == 1).execute().first()192(1, u'admin', u'admin@localhost')193194These results are also dict-like tuples:195196>>> r = users.select(users.c.id == 1).execute().first()197>>> r['name']198u'admin'199Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 200why, one step back200You can also pass strings of SQL statements to theCorrected order of the tutorialArmin Ronacherbefore adoption8489994
lines 201–207why, one step back201:meth:`~sqlalchemy.engine.base.Connection.execute` method:202203>>> engine.execute('select * from users where id = :1', [1]).first()204(1, u'admin', u'admin@localhost')205206For more information about SQLAlchemy, head over to the207`website <http://sqlalchemy.org/>`_.