Skip to content

SQLAlchemy session not being removed between client requests #32

@joshma

Description

@joshma

Because of the pushed app context before each test case, multiple client requests within a test will see each other's (un-committed) sessions. This goes against the docs:

Another gotcha is that Flask-SQLAlchemy also removes the session instance at the end of every request (as should any threadsafe application using SQLAlchemy with scoped_session). Therefore the session is cleared along with any objects added to it every time you call client.get() or another client method.

Here's a test case that fails:

python
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.testing import TestCase

app = Flask(name)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
@app.route('/')
def index():
u = db.session.query(User).first()
u.name = 'bob'
return ''

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)

class SessionTest(TestCase):

def create_app(self):
return app

def test_remove(self):
db.drop_all()
db.create_all()

u = User()
u.name = 'joe'
db.session.add(u)
db.session.commit()
client = app.test_client()
client.get('/')
assert u.name == 'joe' # fails!
assert u not in db.session # would fail if it reached here

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions