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 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 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# The following produces DetachedInstanceError
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
# db = SQLAlchemy(app, session_options={
# 'expire_on_commit': False
# })
class Foo(db.Model):
id = db.Column(db.Integer, primary_key=True)
db.create_all()
foo = Foo()
db.session.add(foo)
db.session.commit()
print(foo.id)
I have ran the above code on my computer, but it didn't raise a DetachedInstanceError
,the flask version on my computer is:
Flask==0.12
Flask-SQLAlchemy==2.2
SQLAlchemy==1.1.6
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for sharing. How do you run Flask? Uwsgi? Multi-thread? Multi-process?