I have the following SQLAlchemy Model:
class MyObject2(db.Model, Timestamp):
id = db.Column(UUIDType(binary=False), nullable=False, primary_key=True)
myobj1_id = db.Column(UUIDType(binary=False), db.ForeignKey(MyObject1.id), nullable=False)
name = db.Column(db.String(25))
def __init__(self, myobj1_id, name=None):
self.id = uuid.uuid4()
self.myobj1_id = myobj1_id
self.name = name
@classmethod
def create(cls, myobj1, name=None):
try:
myobj2 = cls(myobj1_id=myobj1.id, name=name)
db.session.add(myobj2)
db.session.commit()
print myobj2 #<=========== LOOK AT THIS LINE!
return myobj2
except Exception:
db.session.rollback()
raise
finally:
db.session.close()
Notice that there is an extraneous print statement in there. See? It doesn't really do anything. Oh well.
Now, here is the code that calls the create()
method to create an instance of the model:
myobj2 = MyObject2.create(myobj1=myobj1, name='Hello')
serialized_myobj_2 = MyObject2Serializer(myobj2).data
All this works fine. But as soon as I remove the unnecessary print statement, I get the following error in the last line of the caller:
Instance <MyObject2 at 0x7ff804ac5710> is not bound to a Session; attribute refresh operation cannot proceed
Why? How does the absence of the print statement cause this bug?
When I googled around for this error, I found this post. But the solution given there -- to call session.expunge_all() right before
session.close()` -- didn't work for me.
What's the solution to getting rid of that print statement without breaking my code?