Skip to content

Instantly share code, notes, and snippets.

@p-lewis
Last active November 9, 2015 19:50
Show Gist options
  • Save p-lewis/deb498bdfb6172bf0013 to your computer and use it in GitHub Desktop.
Save p-lewis/deb498bdfb6172bf0013 to your computer and use it in GitHub Desktop.
Sample after_flush_postexec session event
from __future__ import print_function
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = sa.create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base()
class Person(Base):
__tablename__ = 'person'
person_id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.Unicode)
def __repr__(self):
return "<Person {}>".format(self.name)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
p = Person(name="P Body")
@sa.event.listens_for(session, "after_flush_postexec")
def handle_after_flush_postexec(session, flush_context):
print("In handler, p: {}".format(p))
renamed = session.info.pop('RENAMED', False)
if not renamed:
p.name += "*"
session.info['RENAMED'] = True
session.add(p)
session.flush()
print("session.dirty: {}".format(session.dirty))
print("session.info: {}".format(session.info))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment