Table Of Contents

Previous topic

Flask-Login Integration

Next topic

Modules

This Page

Flask-SQLAlchemy Integration

Here we’ll go through the extension’s official documentation (as of version 1.0) and correlate items with flask-kit code.

Not only it should help us to master the application architecture, but it will also help us to add features add upgrade to future versions of the extension.

Configuration

The extension provides several configuration keys

We set SQLALCHEMY_DATABASE_URI in settings which will be loaded in app.app or testing.KitTestCase.create_app().

If needed, check the Connection URI Format .

As for other extensions, the engine is instanciated in module ext (ext.db) like this:

db = SQLAlchemy()

Note that the application object is not supplied here. As explained in Introduction into Contexts, the binding can be done later by the init_app() method.

In Flask-kit, it done by the private method helpers.AppFactory._bind_extensions() for all extensions registered in settings.BaseConfig.EXTENSIONS.

Database creation (flask.ext.sqlalchemy.SQLAlchemy.create_all()) is done in manage.init_data() and in testing.KitTestCase.create_app() .

Declaring Models

See Declaring Models for full reference.

We declare our user model in base.models.User .

Instead of inheriting only from flask.ext.sqlalchemy.Model, our class is also derived from flask.ext.login.UserMixin for Flask-Login Integration as well as from our custom base.models.CRUDMixin (see below).

Select, Insert, Delete

Inserting Records

Inserting data into the database is a three step process:

  1. Create the Python object
  2. Add it to Flask-SQLAlchemy the session
  3. Commit the Flask-SQLAlchemy session
>>> from yourapp import User
>>> me = User('admin', 'admin@example.com')
>>> db.session.add(me)
>>> db.session.commit()

This is what is done in the base.models.CRUDMixin.create() method, which shares the save() part with base.models.CRUDMixin.update(), the commit being optional to allow rollback or optimization.

The object’s id will be set by sqlalchemy at commit time.

Deleting Records

Deleting records is very similar, instead of add() use delete():

>>> db.session.delete(me)
>>> db.session.commit()

This is what is done in the base.models.CRUDMixin.delete() method,

Querying Records

This is done through class methods, e.g.