Object is already attached to session

3,087 views
Skip to first unread message

mg

unread,
Apr 16, 2008, 3:55:24 PM4/16/08
to sqlalchemy
I have a couple of threads that are working on the same objects,
passing them back and forth in queues. I have just started testing
with the Sqlalchemy parts turned on, and I am getting the already
attached to session message. Also of note is that I am using the
Elixir declarative layer, although I don't think that is causing the
problem. Here is a basic example of what I am doing.

queue = Queue()

class History(Entity):
status_id = Field(Integer)
text = Field(Text)
using_options(tablename='history', autosetup=True)
using_table_options(useexisting=True)

class Worker(threading.Thread):
def run(self):
items = History.query.all()
for item in item:
queue.put(item)
for i in range(pool_size):
consumer = Consumer(self.getName())
consumer.start()

class Consumer(threading.Thread):
def run(self):
item = queue.get_nowait()
if True:
item.status_id = 1
else:
item.status_id = 2
item.update()
item.flush()

when I try to update I get: InvalidRequestError: Object
'History@0x142d4b0' is already attached to session '21222960' (this is
'21223440')

any help would be greatly appreciated.

thanks,
Matt

bollwyvl

unread,
Jun 12, 2008, 10:58:21 AM6/12/08
to sqlalchemy
I am running into similar problems, adding to the complexity the
threadpool module.

Here's a post that might help:
http://blog.uxpython.com/blog/web/view/116

I am still running into problems, however, based on parent/child
relationships... i think the answer lies in the sqlalchemy `cascade`
property, but I as yet have not found a way to modify that directly in
the Elixir layer.

Michael Bayer

unread,
Jun 12, 2008, 11:06:14 AM6/12/08
to sqlal...@googlegroups.com

if you're passing objects between threads with corresponding
contextual sessions, you need to be expunging those objects from the
session in which they're present before using them in another
session. Use Session.expunge() for this.


Gaetan de Menten

unread,
Jun 13, 2008, 7:59:56 AM6/13/08
to sqlal...@googlegroups.com

I'm not sure the cascade "property" is the answer to Matt's problem
but in any case, you can use the "cascade" argument on Elixir
relationships exactly as you do with SQLAlchemy's relation(). In fact
any argument not specifically used by Elixir's relationships is
forwarded to the relation() construct.

--
Gaëtan de Menten
http://openhex.org

Reply all
Reply to author
Forward
0 new messages