Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with SqlAlchemy - "Parent instance <SomeClass> is not bound to a Session; lazy load operation..."

I have a small thrift server in python that I use do some fast lookups. The server queries mysql via SqlAlchemy on the first request and shoves all returned objects into a dictionary so on subsequent requests no DB call is needed. I just get the object from the dict and then call some of the object methods needed to give the proper response.

Initially, everything is fine. However, after the server runs a while, I am getting this exception when accessing the sqlalchemy object methods:

Parent instance is not bound to a Session; lazy load operation of attribute 'rate' cannot proceed.

Strange, because I set eagerload('rate').

I cannot really see a pattern to this behavior, it only affects some objects. However, once it does affect an object it will continue to do so on each request until I restart my python server.

Any ideas?

like image 593
Tony Avatar asked Nov 23 '10 05:11

Tony


1 Answers

You probably cache objects between the requests, and when the commit happens, session object is getting cleared, invalidating your objects. If you start your server via some multithreaded web server that starts workers as needed, that explains why there's no pattern. If you dont want to get the bottom of this and just need a quick fix, this will always work:

if obj not in session:
    obj = session.query(ObjClass).get(obj.id)

The proper solution would be to make sure you don't cache objects between requests.

like image 74
letitbee Avatar answered Sep 24 '22 04:09

letitbee