sqlalchemy_helpers.flask_ext module

Flask integration of database management.

class sqlalchemy_helpers.flask_ext.DatabaseExtension(app=None, base_model=None)[source]

Bases: object

A Flask extension to configure the database manager according the the app’s configuration.

It cleans up database connections at the end of the requests, and creates the CLI endpoint to sync the database schema.

before_request()[source]

Prepare the database manager at the start of each request.

This is necessary to allow access to the Model.get_* methods.

init_app(app, base_model=None)[source]

Initialize the extention on the provided Flask app

Parameters:

app (flask.Flask) – the Flask application.

property manager

the instance of the database manager.

Type:

DatabaseManager

property session

the database Session instance to use.

Type:

sqlalchemy.session.Session

teardown(exception)[source]

Close the database connection at the end of each requests.

sqlalchemy_helpers.flask_ext.first_or_404(query, description=None)[source]

Like query.first but aborts with 404 if not found.

Parameters:
  • query (sqlalchemy.orm.Query) – a query to retrieve.

  • description (str, optional) – a message for the 404 error if no records are found.

sqlalchemy_helpers.flask_ext.get_or_404(Model, pk, description=None)[source]

Like query.get but aborts with 404 if not found.

Parameters:
  • Model (manager.Base) – a model class.

  • pk (int or str) – the primary key of the desired record.

  • description (str, optional) – a message for the 404 error if not found.

sqlalchemy_helpers.flask_ext.get_url_from_app(app_factory)[source]

Get the DB URI from the app configuration

Create the application if it hasn’t been created yet. This is useful in Alembic’s env.py.

Args: app_factory (callable): the Flask application factory, to be called if this function is

called outside of and application context.