0

I have a table containing device information (there is an id attribute which is the primary key and is autoassigned by DB), and I run the following code:

    session.autoflush = False
    try:
        devices = model.Device.get_all_by_name(session, dev_data.index.tolist())
        for idx, device in enumerate(devices):
            device.update(dev_data.ix[device.name])
            if 0 == idx % 500 and idx != 0:
                session.flush()
    except Exception as exp:
        # exception handling here
    else:
        session.commit()
        session.expunge_all()
        # calling the next line throws 'Instance not bound to a session' error
        logger.debug('Device info after expunge: {}'.format(devices[-1].name))
    finally:
        session.close()

Whenever I try to access an attribute of one of the devices, an exeption is thrown, however I suppose that expunge_all() should detach the objects, and upon commit or flush all python object should be snychronized, right?

Hodossy Szabolcs
  • 1,598
  • 3
  • 18
  • 34
  • And model.Device is an automapped class, that I forgot to mention – Hodossy Szabolcs May 04 '17 at 07:25
  • Detached instances [cannot refresh expired attributes](http://docs.sqlalchemy.org/en/latest/orm/session_state_management.html#quickie-intro-to-object-states), and ["whenever `Session.commit()` or `Session.rollback()` is called, all objects within the `Session` are expired"](http://docs.sqlalchemy.org/en/latest/orm/session_state_management.html#when-to-expire-or-refresh). – Ilja Everilä May 04 '17 at 07:28
  • Thanks, adding expire_on_commit=False to session constructor solved the problem – Hodossy Szabolcs May 04 '17 at 08:07

0 Answers0