@event.listens_for(Session, 'before_flush')
def before_flush(session, flush_context, instances):
    for instance in session.dirty:
        if (not isinstance(instance, Versioned)):
            continue
        if (not session.is_modified(instance, passive=True)):
            continue
        if (not attributes.instance_state(instance).has_identity):
            continue
        instance.new_version(session)
        session.add(instance)
@event.listens_for(Session, 'before_flush')
def before_flush(session, flush_context, instances):
    for instance in session.dirty:
        if (not isinstance(instance, Versioned)):
            continue
        if (not session.is_modified(instance, passive=True)):
            continue
        if (not attributes.instance_state(instance).has_identity):
            continue
        instance.new_version(session)
        session.add(instance)