Skip to content
Myr

sqlalchemy.rst

This file

Path

docs/patterns/sqlalchemy.rst

100 lines · 3.2 KiB

Last changed by

Breaking docs up into smaller piecesArmin Ronacherbefore adoption123a1ad

History of this file

Take it

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`).9Although that is not necessary but makes a lot of sense.1011There are three very common ways to use SQLAlchemy.  I will outline each12of them here:1314Declarative15-----------1617The declarative extension in SQLAlchemy is the most recent method of using18SQLAlchemy.  It allows you to define tables and models in one go, similar19to how Django works.  In addition to the following text I recommend the20official documentation on the `declarative`_ extension.2122Here the example `database.py` module for your application::2324    from sqlalchemy import create_engine25    from sqlalchemy.orm import scoped_session, sessionmaker26    from sqlalchemy.ext.declarative import declarative_base2728    engine = create_engine('sqlite:////tmp/test.db')29    db_session = scoped_session(sessionmaker(autocommit=False,30                                             autoflush=False,31                                             bind=engine)) 32    Base = declarative_base()33    Base.query = db_session.query_property()3435    def init_db():36        Base.metadata.create_all(bind=engine)3738To define your models, just subclass the `Base` class that was created by39the code above.  If you are wondering why we don't have to care about40threads here (like we did in the SQLite3 example above with the41:data:`~flask.g` object): that's because SQLAlchemy does that for us42already with the :class:`~sqlalchemy.orm.scoped_session`.4344To use SQLAlchemy in a declarative way with your application, you just45have to put the following code into your application module.  Flask will46automatically remove database sessions at the end of the request for you::4748    from yourapplication.database import db_session4950    @app.after_request51    def shutdown_session(response):52        db_session.remove()53        return response5455Here an example model (put that into `models.py` for instance)::5657    from sqlalchemy import Column, Integer, String58    from yourapplication.database import Base5960    class User(Base):61        __tablename__ = 'users'62        id = Column(Integer, primary_key=True)63        name = Column(String(50), unique=True)64        email = Column(String(120), unique=True)6566        def __init__(self, name=None, email=None):67            self.name = name68            self.email = email6970        def __repr__(self):71            return '<User %r>' % (self.name, self.email)7273You can insert entries into the database like this then:7475>>> from yourapplication.database import db_session76>>> from yourapplication.models import User77>>> u = User('admin', 'admin@localhost')78>>> db_session.add(u)79>>> db_session.commit()8081Querying is simple as well:8283>>> User.query.all()84[<User u'admin'>]85>>> User.query.filter(User.name == 'admin').first()86<User u'admin'>8788.. _SQLAlchemy: http://www.sqlalchemy.org/89.. _declarative:90   http://www.sqlalchemy.org/docs/reference/ext/declarative.html9192Manual Object Relational Mapping93--------------------------------9495*coming soon*9697SQL Abstraction Layer98---------------------99100*coming soon*