sqlalchemy.rst
This file
Path
docs/patterns/sqlalchemy.rst
215 lines · 7.2 KiB
Last changed by
remove unused ref directivesDavid Lordbefore adoption171aabc
History of this fileTake it
The walk stopped after 200 commits: lines older than 4f3dbb3 point at it.
Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 1–5why, one step back1SQLAlchemy in Flask2===================34Many people prefer `SQLAlchemy`_ for database access. In this case it's5encouraged to use a package instead of a module for your flask applicationremove unused ref directivesDavid Lordbefore adoption171aabc
lines 6–7why, one step back6and drop the models into a separate module (:doc:`packages`). While that7is not necessary, it makes a lot of sense.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 8–22why, one step back89There are four very common ways to use SQLAlchemy. I will outline each10of them here:1112Flask-SQLAlchemy Extension13--------------------------1415Because SQLAlchemy is a common database abstraction layer and object16relational mapper that requires a little bit of configuration effort,17there is a Flask extension that handles that for you. This is recommended18if you want to get started quickly.1920You can download `Flask-SQLAlchemy`_ from `PyPI21<https://pypi.org/project/Flask-SQLAlchemy/>`_.22Merge branch '1.0.x'David Lordbefore adoption1351d0a
line 23why, one step back23.. _Flask-SQLAlchemy: https://flask-sqlalchemy.palletsprojects.com/Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 24–39why, one step back242526Declarative27-----------2829The declarative extension in SQLAlchemy is the most recent method of using30SQLAlchemy. It allows you to define tables and models in one go, similar31to how Django works. In addition to the following text I recommend the32official documentation on the `declarative`_ extension.3334Here's the example :file:`database.py` module for your application::3536 from sqlalchemy import create_engine37 from sqlalchemy.orm import scoped_session, sessionmaker38 from sqlalchemy.ext.declarative import declarative_base39Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 40why, one step back40 engine = create_engine('sqlite:////tmp/test.db')Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 41–86why, one step back41 db_session = scoped_session(sessionmaker(autocommit=False,42 autoflush=False,43 bind=engine))44 Base = declarative_base()45 Base.query = db_session.query_property()4647 def init_db():48 # import all modules here that might define models so that49 # they will be registered properly on the metadata. Otherwise50 # you will have to import them first before calling init_db()51 import yourapplication.models52 Base.metadata.create_all(bind=engine)5354To define your models, just subclass the `Base` class that was created by55the code above. If you are wondering why we don't have to care about56threads here (like we did in the SQLite3 example above with the57:data:`~flask.g` object): that's because SQLAlchemy does that for us58already with the :class:`~sqlalchemy.orm.scoped_session`.5960To use SQLAlchemy in a declarative way with your application, you just61have to put the following code into your application module. Flask will62automatically remove database sessions at the end of the request or63when the application shuts down::6465 from yourapplication.database import db_session6667 @app.teardown_appcontext68 def shutdown_session(exception=None):69 db_session.remove()7071Here is an example model (put this into :file:`models.py`, e.g.)::7273 from sqlalchemy import Column, Integer, String74 from yourapplication.database import Base7576 class User(Base):77 __tablename__ = 'users'78 id = Column(Integer, primary_key=True)79 name = Column(String(50), unique=True)80 email = Column(String(120), unique=True)8182 def __init__(self, name=None, email=None):83 self.name = name84 self.email = email8586 def __repr__(self):Merge pull request #3406 from erfanio/f-string-docsDavid Lordbefore adoption2659f0a
line 87why, one step back87 return f'<User {self.name!r}>'Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 88–104why, one step back8889To create the database you can use the `init_db` function:9091>>> from yourapplication.database import init_db92>>> init_db()9394You can insert entries into the database like this:9596>>> from yourapplication.database import db_session97>>> from yourapplication.models import User98>>> u = User('admin', 'admin@localhost')99>>> db_session.add(u)100>>> db_session.commit()101102Querying is simple as well:103104>>> User.query.all()Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 105why, one step back105[<User 'admin'>]Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 106why, one step back106>>> User.query.filter(User.name == 'admin').first()Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 107why, one step back107<User 'admin'>Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 108–109why, one step back108109.. _SQLAlchemy: https://www.sqlalchemy.org/remove unused ref directivesDavid Lordbefore adoption171aabc
line 110why, one step back110.. _declarative: https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 111–126why, one step back111112Manual Object Relational Mapping113--------------------------------114115Manual object relational mapping has a few upsides and a few downsides116versus the declarative approach from above. The main difference is that117you define tables and classes separately and map them together. It's more118flexible but a little more to type. In general it works like the119declarative approach, so make sure to also split up your application into120multiple modules in a package.121122Here is an example :file:`database.py` module for your application::123124 from sqlalchemy import create_engine, MetaData125 from sqlalchemy.orm import scoped_session, sessionmaker126Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 127why, one step back127 engine = create_engine('sqlite:////tmp/test.db')Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 128–158why, one step back128 metadata = MetaData()129 db_session = scoped_session(sessionmaker(autocommit=False,130 autoflush=False,131 bind=engine))132 def init_db():133 metadata.create_all(bind=engine)134135As in the declarative approach, you need to close the session after136each request or application context shutdown. Put this into your137application module::138139 from yourapplication.database import db_session140141 @app.teardown_appcontext142 def shutdown_session(exception=None):143 db_session.remove()144145Here is an example table and model (put this into :file:`models.py`)::146147 from sqlalchemy import Table, Column, Integer, String148 from sqlalchemy.orm import mapper149 from yourapplication.database import metadata, db_session150151 class User(object):152 query = db_session.query_property()153154 def __init__(self, name=None, email=None):155 self.name = name156 self.email = email157158 def __repr__(self):Merge pull request #3406 from erfanio/f-string-docsDavid Lordbefore adoption2659f0a
line 159why, one step back159 return f'<User {self.name!r}>'Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 160–178why, one step back160161 users = Table('users', metadata,162 Column('id', Integer, primary_key=True),163 Column('name', String(50), unique=True),164 Column('email', String(120), unique=True)165 )166 mapper(User, users)167168Querying and inserting works exactly the same as in the example above.169170171SQL Abstraction Layer172---------------------173174If you just want to use the database system (and SQL) abstraction layer175you basically only need the engine::176177 from sqlalchemy import create_engine, MetaData, Table178Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 179why, one step back179 engine = create_engine('sqlite:////tmp/test.db')Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 180–199why, one step back180 metadata = MetaData(bind=engine)181182Then you can either declare the tables in your code like in the examples183above, or automatically load them::184185 from sqlalchemy import Table186187 users = Table('users', metadata, autoload=True)188189To insert data you can use the `insert` method. We have to get a190connection first so that we can use a transaction:191192>>> con = engine.connect()193>>> con.execute(users.insert(), name='admin', email='admin@localhost')194195SQLAlchemy will automatically commit for us.196197To query your database, you use the engine directly or use a connection:198199>>> users.select(users.c.id == 1).execute().first()Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 200why, one step back200(1, 'admin', 'admin@localhost')Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 201–205why, one step back201202These results are also dict-like tuples:203204>>> r = users.select(users.c.id == 1).execute().first()205>>> r['name']Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 206why, one step back206'admin'Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 207–211why, one step back207208You can also pass strings of SQL statements to the209:meth:`~sqlalchemy.engine.base.Connection.execute` method:210211>>> engine.execute('select * from users where id = :1', [1]).first()Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 212why, one step back212(1, 'admin', 'admin@localhost')Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 213–215why, one step back213214For more information about SQLAlchemy, head over to the215`website <https://www.sqlalchemy.org/>`_.