sqlalchemy.rst
This file
Path
docs/patterns/sqlalchemy.rst
215 lines · 7.2 KiB
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than 2fa8eb3 point at it.
Merge pull request #3684 from MLH-Fellowship/3628-duplicate-headersDavid Lordbefore adoption2fa8eb3
lines 1–215why, 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 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, sessionmaker38 from sqlalchemy.ext.declarative import declarative_base3940 engine = create_engine('sqlite:////tmp/test.db')41 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):87 return f'<User {self.name!r}>'8889To 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()105[<User 'admin'>]106>>> User.query.filter(User.name == 'admin').first()107<User 'admin'>108109.. _SQLAlchemy: https://www.sqlalchemy.org/110.. _declarative: https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/111112Manual 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, sessionmaker126127 engine = create_engine('sqlite:////tmp/test.db')128 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):159 return f'<User {self.name!r}>'160161 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, Table178179 engine = create_engine('sqlite:////tmp/test.db')180 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()200(1, 'admin', 'admin@localhost')201202These results are also dict-like tuples:203204>>> r = users.select(users.c.id == 1).execute().first()205>>> r['name']206'admin'207208You 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()212(1, 'admin', 'admin@localhost')213214For more information about SQLAlchemy, head over to the215`website <https://www.sqlalchemy.org/>`_.