Flask - Resolve SQLAlchemy "instance is not bound to a session"
by
Jeremy Canfield |
Updated: August 05 2023
| Flask articles
Let's say something like this is being returned.
sqlalchemy.orm.exc.DetachedInstanceError: Instance <users at 0x1ff9aa91350> is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: https://sqlalche.me/e/14/bhk3)
In this example, "users" is a class, perhaps something like this.
from . import db
class users(db.Model):
id = db.Column(db.Integer, nullable=False, unique=True, primary_key=True)
firstname = db.Column(db.String(20), nullable=False, unique=True)
lastname = db.Column(db.String(40), nullable=False, unique=False)
state = db.Column(db.String(10), nullable=False, unique=False)
Here is an example that would produce this issue. After session.close() there are print statements using data. The data object was "removed" by session.close().
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func, exc
db = SQLAlchemy()
def app_obj():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
app.config["SQLALCHEMY_ECHO"] = True
app.config["SQLALCHEMY_RECORD_QUERIES"] = True
db.init_app(app)
with app.app_context():
db.create_all()
from .models import users
data = users.query.filter_by(email='john.doe@example.com').first()
print("before data.email = " + str(data.email))
print("before data.firstname = " + str(data.firstname))
print("before data.lastname = " + str(data.lastname))
print("before data.state = " + str(data.state))
data.state = 'active'
try:
db.session.commit()
except exc.SQLAlchemyError as sqlalchemyerror:
print("got the following SQLAlchemyError: " + str(sqlalchemyerror))
except Exception as exception:
print("got the following Exception: " + str(exception))
finally:
db.session.close()
print("after data.email = " + str(data.email))
print("after data.firstname = " + str(data.firstname))
print("after data.lastname = " + str(data.lastname))
print("after data.state = " + str(data.state))
return app
Did you find this article helpful?
If so, consider buying me a coffee over at
Comments
October 30 2023 by Shan
Thank you so much, was stuck on this, exact cause of this error, was my print statement in try{ catch}