Skip to content
Myr

sqlalchemy.rst

This file

Path

docs/patterns/sqlalchemy.rst

213 lines · 7.1 KiB

Last changed by

merge app and request context (#5812)David Lordbefore adoptionadf3636

History of this file

Take it

1SQLAlchemy 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 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_engine37    from sqlalchemy.orm import scoped_session, sessionmaker, declarative_base3839    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 after each app135context. Put this into your application module::136137    from yourapplication.database import db_session138139    @app.teardown_appcontext140    def shutdown_session(exception=None):141        db_session.remove()142143Here is an example table and model (put this into :file:`models.py`)::144145    from sqlalchemy import Table, Column, Integer, String146    from sqlalchemy.orm import mapper147    from yourapplication.database import metadata, db_session148149    class User(object):150        query = db_session.query_property()151152        def __init__(self, name=None, email=None):153            self.name = name154            self.email = email155156        def __repr__(self):157            return f'<User {self.name!r}>'158159    users = Table('users', metadata,160        Column('id', Integer, primary_key=True),161        Column('name', String(50), unique=True),162        Column('email', String(120), unique=True)163    )164    mapper(User, users)165166Querying and inserting works exactly the same as in the example above.167168169SQL Abstraction Layer170---------------------171172If you just want to use the database system (and SQL) abstraction layer173you basically only need the engine::174175    from sqlalchemy import create_engine, MetaData, Table176177    engine = create_engine('sqlite:////tmp/test.db')178    metadata = MetaData(bind=engine)179180Then you can either declare the tables in your code like in the examples181above, or automatically load them::182183    from sqlalchemy import Table184185    users = Table('users', metadata, autoload=True)186187To insert data you can use the `insert` method.  We have to get a188connection first so that we can use a transaction:189190>>> con = engine.connect()191>>> con.execute(users.insert(), name='admin', email='admin@localhost')192193SQLAlchemy will automatically commit for us.194195To query your database, you use the engine directly or use a connection:196197>>> users.select(users.c.id == 1).execute().first()198(1, 'admin', 'admin@localhost')199200These results are also dict-like tuples:201202>>> r = users.select(users.c.id == 1).execute().first()203>>> r['name']204'admin'205206You can also pass strings of SQL statements to the207:meth:`~sqlalchemy.engine.base.Connection.execute` method:208209>>> engine.execute('select * from users where id = :1', [1]).first()210(1, 'admin', 'admin@localhost')211212For more information about SQLAlchemy, head over to the213`website <https://www.sqlalchemy.org/>`_.