def get_config(): db_session = DbSession() # Prevent expiration after the session is closed or object is made transient or disconnected db_session.expire_on_commit = False ccm = None try: # Should be only one, return last modified ccm = db_session.query(ChargerConfigModel) \ .order_by(desc(ChargerConfigModel.modified_at)) \ .first() # Detach (not transient) from database, allows saving in other Threads # https://docs.sqlalchemy.org/en/14/orm/session_api.html#sqlalchemy.orm.make_transient_to_detached make_transient(ccm) make_transient_to_detached(ccm) except InvalidRequestError as e: ChargerConfigModel.__cleanupDbSession(db_session, ChargerConfigModel.__class__) except Exception as e: # Nothing to roll back ChargerConfigModel.logger.error( "Could not query from {} table in database".format( ChargerConfigModel.__tablename__), exc_info=True) raise DbException( "Could not query from {} table in database".format( ChargerConfigModel.__tablename__)) return ccm
def save(self): self.logger.debug(".save()") db_session = DbSession() # Prevent expiration after the session is closed or object is made transient or disconnected db_session.expire_on_commit = False try: # No need to 'add', committing this class db_session.add(self) db_session.commit() # Keep it detached make_transient(self) make_transient_to_detached(self) except InvalidRequestError as e: self.logger.error( ".save() - Could not commit to {} table in database".format( self.__tablename__), exc_info=True) self.__cleanupDbSession(db_session, self.__class__.__name__) except Exception as e: db_session.rollback() self.logger.error( ".save() - Could not commit to {} table in database".format( self.__tablename__), exc_info=True) raise DbException( "Could not commit to {} table in database".format( self.__tablename__))
def delete(self): db_session = DbSession() db_session.expire_on_commit = True try: db_session.delete(self) db_session.commit() # Keep it detached make_transient(self) make_transient_to_detached(self) except InvalidRequestError as e: self.__cleanupDbSession(db_session, self.__class__.__name__) except Exception as e: db_session.rollback() self.logger.error( "Could not delete from {} table in database".format( self.__tablename__), exc_info=True) raise DbException( "Could not delete from {} table in database".format( self.__tablename__))