How can I get the previous state of the ORA object of the SQLAlchemy object after updating db?

The problem is that I cannot figure out how to use SQLAlchemy to notify me when an object transitions to a new state.

I am using SQLAlchemy ORM (declarative) to update an object:

class Customer(declarative_base()):

    __table_name__ = "customer"

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

I want to know when an object enters a state. In particular, after the UPDATE was released and when the state changed. For instance. Customer.status == 'registered', and earlier he had a different condition.

I am currently doing this with an attribute event 'set':

from sqlalchemy import event
from model import Customer

def on_set_attribute(target, value, oldvalue, initiator):
    print target.status
    print value
    print oldvalue

event.listen(
        Customer.status,
        'set',
        on_set_attribute,
        propagate=True,
        active_history=True)

, "set", , value oldvalue. , target , .

? !

+5
2

"after_flush" SessionEvent "set" AttributeEvent.

agronholm, SessionEvent, oldvalue.

:

def get_old_value(attribute_state):
    history = attribute_state.history
    return history.deleted[0] if history.deleted else None


def trigger_attribute_change_events(object_):
    for mapper_property in object_mapper(object_).iterate_properties:
        if isinstance(mapper_property, ColumnProperty):
            key = mapper_property.key
            attribute_state = inspect(object_).attrs.get(key)
            history = attribute_state.history

            if history.has_changes():
                value = attribute_state.value
                # old_value is None for new objects and old value for dirty objects
                old_value = get_old_value(attribute_state)
                handler = registry.get(mapper_property)
                if handler:
                    handler(object_, value, old_value)


def on_after_flush(session, flush_context):
    changed_objects = session.new.union(session.dirty)
    for o in changed_objects:
        trigger_attribute_change_events(o)

event.listen(session, "after_flush", on_after_flush)

registry - , MapperProperty . session, event, inspect object_mapper - sqlalchemy.

+10
+2

All Articles