Skip to content
Myr

sqlalchemy.rst

This file

Path

docs/patterns/sqlalchemy.rst

214 lines · 7.1 KiB

Last changed by

Merge branch '2.3.x'David Lordbefore adoptioncc55d7b

History of this file

Take it

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

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 1–36why, one step back
1SQLAlchemy in Flask
2===================34Many people prefer `SQLAlchemy`_ for database access. In this case it's5encouraged to use a package instead of a module for your flask application6and drop the models into a separate module (:doc:`packages`). While that7is not necessary, it makes a lot of sense.89There 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/>`_.2223.. _Flask-SQLAlchemy: https://flask-sqlalchemy.palletsprojects.com/242526Declarative27-----------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_engine

Merge branch '2.3.x'David Lordbefore adoptioncc55d7b

line 37why, one step back
37 from sqlalchemy.orm import scoped_session, sessionmaker, declarative_base

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 38–214why, one step back
38
39 engine = create_engine('sqlite:////tmp/test.db')40 db_session = scoped_session(sessionmaker(autocommit=False,41 autoflush=False,42 bind=engine))43 Base = declarative_base()44 Base.query = db_session.query_property()4546 def init_db():47 # import all modules here that might define models so that48 # they will be registered properly on the metadata. Otherwise49 # you will have to import them first before calling init_db()50 import yourapplication.models51 Base.metadata.create_all(bind=engine)5253To define your models, just subclass the `Base` class that was created by54the code above. If you are wondering why we don't have to care about55threads here (like we did in the SQLite3 example above with the56:data:`~flask.g` object): that's because SQLAlchemy does that for us57already with the :class:`~sqlalchemy.orm.scoped_session`.5859To use SQLAlchemy in a declarative way with your application, you just60have to put the following code into your application module. Flask will61automatically remove database sessions at the end of the request or62when the application shuts down::6364 from yourapplication.database import db_session6566 @app.teardown_appcontext67 def shutdown_session(exception=None):68 db_session.remove()6970Here is an example model (put this into :file:`models.py`, e.g.)::7172 from sqlalchemy import Column, Integer, String73 from yourapplication.database import Base7475 class User(Base):76 __tablename__ = 'users'77 id = Column(Integer, primary_key=True)78 name = Column(String(50), unique=True)79 email = Column(String(120), unique=True)8081 def __init__(self, name=None, email=None):82 self.name = name83 self.email = email8485 def __repr__(self):86 return f'<User {self.name!r}>'8788To create the database you can use the `init_db` function:8990>>> from yourapplication.database import init_db91>>> init_db()9293You can insert entries into the database like this:9495>>> from yourapplication.database import db_session96>>> from yourapplication.models import User97>>> u = User('admin', 'admin@localhost')98>>> db_session.add(u)99>>> db_session.commit()100101Querying is simple as well:102103>>> User.query.all()104[<User 'admin'>]105>>> User.query.filter(User.name == 'admin').first()106<User 'admin'>107108.. _SQLAlchemy: https://www.sqlalchemy.org/109.. _declarative: https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/110111Manual Object Relational Mapping112--------------------------------113114Manual object relational mapping has a few upsides and a few downsides115versus the declarative approach from above. The main difference is that116you define tables and classes separately and map them together. It's more117flexible but a little more to type. In general it works like the118declarative approach, so make sure to also split up your application into119multiple modules in a package.120121Here is an example :file:`database.py` module for your application::122123 from sqlalchemy import create_engine, MetaData124 from sqlalchemy.orm import scoped_session, sessionmaker125126 engine = create_engine('sqlite:////tmp/test.db')127 metadata = MetaData()128 db_session = scoped_session(sessionmaker(autocommit=False,129 autoflush=False,130 bind=engine))131 def init_db():132 metadata.create_all(bind=engine)133134As in the declarative approach, you need to close the session after135each request or application context shutdown. Put this into your136application module::137138 from yourapplication.database import db_session139140 @app.teardown_appcontext141 def shutdown_session(exception=None):142 db_session.remove()143144Here is an example table and model (put this into :file:`models.py`)::145146 from sqlalchemy import Table, Column, Integer, String147 from sqlalchemy.orm import mapper148 from yourapplication.database import metadata, db_session149150 class User(object):151 query = db_session.query_property()152153 def __init__(self, name=None, email=None):154 self.name = name155 self.email = email156157 def __repr__(self):158 return f'<User {self.name!r}>'159160 users = Table('users', metadata,161 Column('id', Integer, primary_key=True),162 Column('name', String(50), unique=True),163 Column('email', String(120), unique=True)164 )165 mapper(User, users)166167Querying and inserting works exactly the same as in the example above.168169170SQL Abstraction Layer171---------------------172173If you just want to use the database system (and SQL) abstraction layer174you basically only need the engine::175176 from sqlalchemy import create_engine, MetaData, Table177178 engine = create_engine('sqlite:////tmp/test.db')179 metadata = MetaData(bind=engine)180181Then you can either declare the tables in your code like in the examples182above, or automatically load them::183184 from sqlalchemy import Table185186 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, 'admin', 'admin@localhost')200201These results are also dict-like tuples:202203>>> r = users.select(users.c.id == 1).execute().first()204>>> r['name']205'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, 'admin', 'admin@localhost')212213For more information about SQLAlchemy, head over to the214`website <https://www.sqlalchemy.org/>`_.