begin_nested() can be used within any of the before_flush(), after_flush(), or 
after_flush_postexec() methods, see below.

What you can't do in *any* of these methods is flush() the Session itself, as 
the Session is already in the "flush state" and it does not support reentrant 
behavior.

Additionally, modifications to the state of the Session regarding objects 
should only happen in before_flush().


from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import event

Base = declarative_base()

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)
    data = Column(String)

@event.listens_for(Session, 'after_flush')
def update_data(session, flush_context):
    with session.begin_nested():
        session.execute(A.__table__.update().values(data='hoho'))

e = create_engine("postgresql://scott:tiger@localhost/test", echo=True)

Base.metadata.create_all(e)

a1 = A(data='foo')
s = Session(e)
s.add(a1)
s.commit()
assert a1.data == 'hoho'


On Aug 30, 2012, at 2:08 AM, Azhar Mashuri wrote:

> Hi, why I cannot call a Session().begin(nested=True) inside an after_flush 
> event? I've tried this inside before_flush and it's work.
> 
> My work flow as below :
> - work on model
> - Session().commit()
> - begin before_flush
>   - begin nested
>      - do an update/delete/insert on related object
>   - commit
> - end before_flush
> - begin after flush
>   - begin nested
>      - do an update/delete/insert on related object
>   - commit
>   - begin nested
>     - create version object every update/deleted object
>   - commit
> - end before_flush
> 
> I use Declarative extension and scoped_session.
> 
> Thanks,
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "sqlalchemy" group.
> To view this discussion on the web visit 
> https://groups.google.com/d/msg/sqlalchemy/-/H0UXpUkeSh0J.
> To post to this group, send email to sqlalchemy@googlegroups.com.
> To unsubscribe from this group, send email to 
> sqlalchemy+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/sqlalchemy?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to