Skip to content
Myr

sqlalchemy.rst

This file

Path

docs/patterns/sqlalchemy.rst

218 lines · 7.2 KiB

Last changed by

f-strings everywhereDavid Lordbefore adoption2ae740d

History of this file

Take it

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

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 1–24why, 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<https://pypi.org/project/Flask-SQLAlchemy/>`_.24

Merge branch '1.0.x'David Lordbefore adoption1351d0a

line 25why, one step back
25.. _Flask-SQLAlchemy: https://flask-sqlalchemy.palletsprojects.com/

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 26–41why, one step back
26
2728Declarative29-----------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's the example :file:`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_base41

remove Python 2 from docsDavid Lordbefore adoption7673835

line 42why, one step back
42 engine = create_engine('sqlite:////tmp/test.db')

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 43–88why, one step back
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():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 will64automatically remove database sessions at the end of the request or65when the application shuts down::6667 from yourapplication.database import db_session6869 @app.teardown_appcontext70 def shutdown_session(exception=None):71 db_session.remove()7273Here is an example model (put this into :file:`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):

Merge pull request #3406 from erfanio/f-string-docsDavid Lordbefore adoption2659f0a

line 89why, one step back
89 return f'<User {self.name!r}>'

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 90–106why, one step back
90
91To 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()

f-strings everywhereDavid Lordbefore adoption2ae740d

line 107why, one step back
107[<User 'admin'>]

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

line 108why, one step back
108>>> User.query.filter(User.name == 'admin').first()

f-strings everywhereDavid Lordbefore adoption2ae740d

line 109why, one step back
109<User 'admin'>

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 110–129why, one step back
110
111.. _SQLAlchemy: https://www.sqlalchemy.org/112.. _declarative:113 https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/114115Manual 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 :file:`database.py` module for your application::126127 from sqlalchemy import create_engine, MetaData128 from sqlalchemy.orm import scoped_session, sessionmaker129

remove Python 2 from docsDavid Lordbefore adoption7673835

line 130why, one step back
130 engine = create_engine('sqlite:////tmp/test.db')

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 131–161why, one step back
131 metadata = MetaData()
132 db_session = scoped_session(sessionmaker(autocommit=False,133 autoflush=False,134 bind=engine))135 def init_db():136 metadata.create_all(bind=engine)137138As in the declarative approach, you need to close the session after139each request or application context shutdown. Put this into your140application module::141142 from yourapplication.database import db_session143144 @app.teardown_appcontext145 def shutdown_session(exception=None):146 db_session.remove()147148Here is an example table and model (put this into :file:`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):

Merge pull request #3406 from erfanio/f-string-docsDavid Lordbefore adoption2659f0a

line 162why, one step back
162 return f'<User {self.name!r}>'

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 163–181why, one step back
163
164 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, MetaData, Table181

remove Python 2 from docsDavid Lordbefore adoption7673835

line 182why, one step back
182 engine = create_engine('sqlite:////tmp/test.db')

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 183–202why, one step back
183 metadata = MetaData(bind=engine)
184185Then you can either declare the tables in your code like in the examples186above, or automatically load them::187188 from sqlalchemy import Table189190 users = Table('users', metadata, autoload=True)191192To insert data you can use the `insert` method. We have to get a193connection first so that we can use a transaction:194195>>> con = engine.connect()196>>> con.execute(users.insert(), name='admin', email='admin@localhost')197198SQLAlchemy will automatically commit for us.199200To query your database, you use the engine directly or use a connection:201202>>> users.select(users.c.id == 1).execute().first()

f-strings everywhereDavid Lordbefore adoption2ae740d

line 203why, one step back
203(1, 'admin', 'admin@localhost')

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 204–208why, one step back
204
205These results are also dict-like tuples:206207>>> r = users.select(users.c.id == 1).execute().first()208>>> r['name']

f-strings everywhereDavid Lordbefore adoption2ae740d

line 209why, one step back
209'admin'

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 210–214why, one step back
210
211You can also pass strings of SQL statements to the212:meth:`~sqlalchemy.engine.base.Connection.execute` method:213214>>> engine.execute('select * from users where id = :1', [1]).first()

f-strings everywhereDavid Lordbefore adoption2ae740d

line 215why, one step back
215(1, 'admin', 'admin@localhost')

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 216–218why, one step back
216
217For more information about SQLAlchemy, head over to the218`website <https://www.sqlalchemy.org/>`_.