Database session and instance

Coaster provides a subclass of Flask-SQLAlchemy with a custom session, and an instance of Flask-SQLAlchemy. If your app has models distributed across modules, you can use coaster’s instance instead of creating a new module solely for a shared dependency. Some HasGeek libraries like nodular and Flask-Commentease depend on this instance for their models.

class coaster.db.CoasterSession(db, autocommit=False, autoflush=True, app=None, **options)[source]

Custom session that provides additional helper methods.

add_and_commit(_instance, **filters)[source]

Add and commit a new instance, gracefully handling failure in case a conflicting entry is already in the database (which may occur due to parallel requests causing race conditions in a production environment with multiple workers).

Returns the instance saved to database if no error occured, or loaded from database using the provided filters if an error occured. If the filters fail to load from the database, the original IntegrityError is re-raised, as it is assumed to imply that the commit failed because of missing or invalid data, not because of a duplicate entry.

Usage: db.session().add_and_commit(instance, **filters) where filters are the parameters passed to Model.query.filter_by(**filters).one() to load the instance.

Parameters:
  • _instance – Instance to commit
  • filters – Filters required to load existing instance from the database in case the commit fails (required)
Returns:

Instance that is in the database

class coaster.db.SQLAlchemy(app=None, use_native_unicode=True, session_options=None, metadata=None)[source]

Subclass of flask.ext.sqlalchemy.SQLAlchemy that uses CoasterSession, providing additional methods in the database session.

create_session(options)[source]

Creates the session using CoasterSession.

coaster.db.db

Instance of SQLAlchemy

Caution

This instance is process-global. Your database models will be shared across all apps running in the same process. Do not run unrelated apps in the same process.