Flask-SQLAlchemy-Session

Flask-SQLALchemy-Session is a tiny library providing an SQLAlchemy scoped session that creates unique sessions per Flask request, following the guidelines documented at Using Custom Created Scopes.

Basic usage

Initialize a flask_scoped_session as you would a scoped_session, with the addition of a Flask app. Then use the resulting session to query models:

from flask import Flask, abort, jsonify
from flask_sqlalchemy_session import flask_scoped_session

app = Flask(__name__)
session = flask_scoped_session(session_factory, app)

@app.route("/users/<int:user_id>")
def user(user_id):
    user = session.query(User).get(user_id)
    if user is None:
        abort(404)
    return flask.jsonify(**user.to_dict())

The current_session is also provided as a convenient accessor to the session of the current request, in the same spirit of request and current_app.

Implementation

The flask_scoped_session is a simple wrapper over the original scoped_session that sets the scope to the Flask application context, using the right scopefunc parameter. The application context is rougly equivalent to a Flask request (more here). The session is destroyed on application context teardown.

Full Example

This is a complete example with SQL Alchemy model and engine initialization, followed by Flask app creation and querying of models within a Flask request.

Declare your models:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    id = Column(Integer, primary_key=True)
    name = Column(String)

    def to_dict(self):
        return {"id": self.id,
                "name": self.name}

Initialize the database engine and session:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine("sqlite://")
session_factory = sessionmaker(bind=engine)

Instantiate a Flask application and query a model within a request:

from flask import Flask, abort, jsonify
from flask_sqlalchemy_session import flask_scoped_session

app = Flask(__name__)
session = flask_scoped_session(session_factory, app)

@app.route("/users/<int:user_id>")
def user(user_id):
    user = session.query(User).get(user_id)
    if user is None:
        abort(404)
    return flask.jsonify(**user.to_dict())

Or use the equivalent current_session:

from flask_sqlalchemy_session import current_session

@app.route("/users/<int:user_id>")
def user(user_id):
    user = current_session.query(User).get(user_id)
    if user is None:
        abort(404)
    return flask.jsonify(**user.to_dict())

Comparison with Flask-SQLAlchemy

The Flask-SQLAlchemy project also provides a request-scoped session, along with much more. It comes an API that acts as a facade over various SQL Alchemy APIs (engines, models, metadata). This API buries the engine/session initialization behind the Flask app initialization, detracts from the original by removing decisions, and tightly couples the data layer with the Flask app. On the good side, it is an API easier to start with than SQL Alchemy itself.

Flask-SQLAlchemySession is not intrusive to the original SQL Alchemy APIs in any way, and does not force you to couple your data layer with your web application. It’s sole purpose is to enable request-scoped sessions on top of your SQL Alchemy constructs.

API

Flask-SQLAlchemy-Session

Provides an SQLAlchemy scoped session that creates unique sessions per Flask request

flask_sqlalchemy_session.current_session

Provides the current SQL Alchemy session within a request.

class flask_sqlalchemy_session.flask_scoped_session(session_factory, app=None)

A scoped_session whose scope is set to the Flask application context.

__init__(session_factory, app=None)
Parameters:
  • session_factory – A callable that returns a Session
  • app – a Flask application
init_app(app)

Setup scoped sesssion creation and teardown for the passed app.

Parameters:app – a Flask application
Fork me on GitHub