Flask Snippets

Lazy SQLAlchemy setup

If you are using the new Flask configuration together with the application factory pattern, one thing you will want to do if using SQLAlchemy is initialize a SQLAlchemy session for different requirements. For example, for unit tests you don't want to use the production database.

Furthermore you may need to use a SQLAlchemy session outside the request scope, for example in the shell.

The scoped_session function, which provides a thread-safe session, expects a factory function. Normally we would use sessionmaker: