Created
July 4, 2014 13:38
-
-
Save krak3n/9fa1268ee0a92a67f71a to your computer and use it in GitHub Desktop.
Avoid DetachedInstanceError in Flask-SQLAlchemy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The following produces DetachedInstanceError | |
app = Flask(__name__) | |
db = SQLAlchemy(app) | |
class Foo(db.Model): | |
id = db.Column(db.Integer, primary_key=True) | |
foo = Foo() | |
db.session.add(foo) | |
db.session.commit() | |
foo.id | |
>>> DetachedInstanceError: Instance <Foo at 0x10741ac10> is not bound to a Session; attribute refresh operation cannot proceed | |
# The following removes DetachedInstanceError | |
app = Flask(__name__) | |
db = SQLAlchemy(app, session_options{ | |
'expire_on_commit': False | |
}) | |
class Foo(db.Model): | |
id = db.Column(db.Integer, primary_key=True) | |
foo = Foo() | |
db.session.add(foo) | |
db.session.commit() | |
foo.id | |
>>> 1 |
I have troubleshooting this issue half day, this is realy help me.
thank you very much!
Thank you very much help. This helped to solve my problem.
But you don't close the session, the commit operation just expire the orm object, why does this lead to produces DetachedInstanceError ?
flask-sqlalchemy auto close when commit ?
Gosh this is a blast from the past @kalelsun 😄 I no longer work with Python or Flash / SQL Alchemy so I can't really answer your question, sorry, of course this very old code at this point so I have no idea if it is still relevant.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have ran the above code on my computer, but it didn't raise a
DetachedInstanceError
,the flask version on my computer is: