sqlalchemy.orm.object_session

Here are the examples of the python api sqlalchemy.orm.object_session taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

85 Examples 7

Page 1 Selected Page 2

Example 1

Project: sqlalchemy-continuum Source File: fetcher.py
    def _next_prev_query(self, obj, next_or_prev='next'):
        session = sa.orm.object_session(obj)

        return (
            session.query(obj.__class__)
            .filter(
                sa.and_(
                    getattr(
                        obj.__class__,
                        tx_column_name(obj)
                    )
                    ==
                    self._transaction_id_subquery(
                        obj, next_or_prev=next_or_prev
                    ),
                    *parent_criteria(obj)
                )
            )
        )

Example 2

Project: sqlalchemy-utils Source File: asserts.py
Function: update_field
def _update_field(obj, field, value):
    session = sa.orm.object_session(obj)
    column = sa.inspect(obj.__class__).columns[field]
    query = column.table.update().values(**{column.key: value})
    session.execute(query)
    session.flush()

Example 3

Project: kittystore Source File: model.py
Function: likes
    @property
    def likes(self):
        session = object_session(self)
        return session.cache.get_or_create(
            str("list:%s:thread:%s:likes" % (self.list_name, self.thread_id)),
            lambda: self._getvotes().filter(Vote.value == 1).count()
            )

Example 4

Project: Camelot Source File: batch_job.py
    def add_strings_to_message( self, strings, color = None ):
        """Add strings to the message of this batch job.
        
        :param strings: a list or generator of strings
        :param color: the html color to be used for the strings (`'red'`, 
        `'green'`, ...), None if the color needs no change. 
        """
        if color:
            strings = [u'<font color="%s">'%color] + strings + [u'</font>']
        session = orm.object_session( self )
        # message might be changed in the orm
        session.commit()
        batch_table = self.__table__
        update = batch_table.update().where( batch_table.c.id == self.id )
        update = update.values( message = sql.func.coalesce( batch_table.c.message, '' ) + sql.bindparam('line') )
        for line in strings:
            session.execute( update, params = {'line':line + '<br/>'} )
        session.commit()

Example 5

Project: Camelot Source File: list_action.py
Function: model_run
    def model_run( self, model_context ):
        from sqlalchemy.orm import object_session
        from camelot.view import action_steps
        obj_getter = yield action_steps.SelectObject( model_context.admin )
        if obj_getter != None:
            obj_to_add = obj_getter()
            for obj in model_context.get_collection():
                if obj_to_add == obj:
                    raise StopIteration()
            model_context._model.append_object( obj_to_add, flush = False )
            yield action_steps.FlushSession( object_session( obj_to_add ) )

Example 6

Project: kittystore Source File: model.py
Function: participants_count
    @property
    def participants_count(self):
        session = object_session(self)
        return session.cache.get_or_create(
            str("list:%s:thread:%s:participants_count"
                % (self.list_name, self.thread_id)),
            lambda: self._get_participants().count())

Example 7

Project: sqlalchemy-continuum Source File: property_mod_tracker.py
    def after_create_version_object(self, uow, parent_obj, version_obj):
        session = sa.orm.object_session(parent_obj)
        is_deleted = parent_obj in session.deleted

        for prop in versioned_column_properties(parent_obj):
            if has_changes(parent_obj, prop.key) or is_deleted:
                setattr(
                    version_obj,
                    prop.key + self.column_suffix,
                    True
                )

Example 8

Project: kittystore Source File: model.py
Function: recent_participants_count
    @property
    def recent_participants_count(self):
        begin_date, end_date = self.get_recent_dates()
        session = object_session(self)
        return session.cache.get_or_create(
            str("list:%s:recent_participants_count" % self.name),
            lambda: get_participants_count_between(session, self.name,
                                                   begin_date, end_date),
            86400)

Example 9

Project: sqlalchemy-utils Source File: observer.py
    def get_callback_args(self, root_obj, callback):
        session = sa.orm.object_session(root_obj)
        objects = [getdotattr(
            root_obj,
            path,
            lambda obj: obj not in session.deleted
        ) for path in callback.fullpath]
        paths = [str(path) for path in callback.fullpath]
        for path in paths:
            if '.' in path or has_changes(root_obj, path):
                return (
                    root_obj,
                    callback.func,
                    objects
                )

Example 10

Project: kittystore Source File: model.py
Function: get_month_activity
    def get_month_activity(self, year, month):
        session = object_session(self)
        begin_date = datetime.datetime(year, month, 1)
        end_date = begin_date + datetime.timedelta(days=32)
        end_date = end_date.replace(day=1)
        participants_count = session.cache.get_or_create(
            str("list:%s:participants_count:%s:%s" % (self.name, year, month)),
            lambda: get_participants_count_between(session, self.name,
                                                   begin_date, end_date),
            )
        threads_count = session.cache.get_or_create(
            str("list:%s:threads_count:%s:%s" % (self.name, year, month)),
            lambda: get_threads_between(session, self.name,
                                        begin_date, end_date).count(),
            )
        Activity = namedtuple('Activity',
                ['year', 'month', 'participants_count', 'threads_count'])
        return Activity(year, month, participants_count, threads_count)

Example 11

Project: Camelot Source File: authentication.py
def get_current_authentication( _obj = None ):
    """Get the currently logged in :class:'AuthenticationMechanism'"""
    global _current_authentication_
    if not hasattr( _current_authentication_, 'mechanism' ) \
        or not _current_authentication_.mechanism \
        or not orm.object_session( _current_authentication_.mechanism ):
            import getpass
            _current_authentication_.mechanism = AuthenticationMechanism.get_or_create( unicode( getpass.getuser(), encoding='utf-8', errors='ignore' ) )
    return _current_authentication_.mechanism

Example 12

Project: Camelot Source File: entity_admin.py
Function: refresh
    @model_function
    def refresh(self, entity_instance):
        """Undo the pending changes to the backend and restore the original
        state"""
        session = orm.object_session( entity_instance )
        if session:
            objects_to_refresh = set([entity_instance])
            self._expand_compounding_objects( objects_to_refresh )
            for obj in objects_to_refresh:
                if obj in session:
                    session.refresh( obj )

Example 13

Project: kittystore Source File: model.py
    @property
    def starting_email(self):
        """Return (and cache) the email starting this thread"""
        session = object_session(self)
        message_id = session.cache.get_or_create(
            str("list:%s:thread:%s:starting_email_id"
                % (self.list_name, self.thread_id)),
            lambda: session.query(Email.message_id).with_parent(self).order_by(
                    Email.in_reply_to != None, Email.date).limit(1).scalar(),
            should_cache_fn=lambda val: val is not None
            )
        if message_id is not None:
            return session.query(Email).get((self.list_name, message_id))

Example 14

Project: Camelot Source File: test_action.py
Function: test_delete_selection
    def test_delete_selection( self ):
        session = orm.object_session( self.context.obj )
        self.assertTrue( self.context.obj in session )
        delete_selection_action = list_action.DeleteSelection()
        delete_selection_action.gui_run( self.gui_context ) 
        list( delete_selection_action.model_run( self.context ) )
        self.assertFalse( self.context.obj in session )

Example 15

Project: autonomie Source File: base.py
Function: print_status
def printstatus(obj):
    """
        print an object's status regarding the sqla's session
    """
    from sqlalchemy.orm import object_session
    from sqlalchemy.orm.util import has_identity
    if object_session(obj) is None and not has_identity(obj):
        print "Sqlalchemy status : transient"
    elif object_session(obj) is not None and not has_identity(obj):
        print "Sqlalchemy status : pending"
    elif object_session(obj) is None and has_identity(obj):
        print "Sqlalchemy status : detached"
    elif object_session(obj) is not None and has_identity(obj):
        print "Sqlalchemy status : persistent"
    else:
        print "Unknown Status"

Example 16

Project: sqlalchemy-continuum Source File: fetcher.py
    def previous_query(self, obj):
        """
        Returns the query that fetches the previous version relative to this
        version in the version history.
        """
        session = sa.orm.object_session(obj)

        return (
            session.query(obj.__class__)
            .filter(
                sa.and_(
                    getattr(obj.__class__, end_tx_column_name(obj))
                    ==
                    getattr(obj, tx_column_name(obj)),
                    *parent_criteria(obj)
                )
            )
        )

Example 17

Project: kittystore Source File: model.py
Function: emails_count
    @property
    def emails_count(self):
        session = object_session(self)
        return session.cache.get_or_create(
            str("list:%s:thread:%s:emails_count"
                % (self.list_name, self.thread_id)),
            lambda: session.query(Email).with_parent(self).count())

Example 18

Project: sqlalchemy-continuum Source File: utils.py
def is_modified_or_deleted(obj):
    """
    Return whether or not some of the versioned properties of given SQLAlchemy
    declarative object have been modified or if the object has been deleted.

    :param obj: SQLAlchemy declarative model object
    """
    session = sa.orm.object_session(obj)
    return is_versioned(obj) and (
        is_modified(obj) or
        obj in chain(session.deleted, session.new)
    )

Example 19

Project: bauble.classic Source File: __init__.py
def delete_or_expunge(obj):
    """
    If the object is in object_session(obj).new then expunge it from the
    session.  If not then session.delete it.
    """
    from sqlalchemy.orm import object_session
    session = object_session(obj)
    if session is None:
        return
    if obj not in session.new:
        logger.debug('delete obj: %s -- %s' % (obj, repr(obj)))
        session.delete(obj)
    else:
        logger.debug('expunge obj: %s -- %s' % (obj, repr(obj)))
        session.expunge(obj)
        del obj

Example 20

Project: sqlalchemy-utils Source File: asserts.py
def _expect_failing_update(obj, field, value, expected_exc):
    try:
        _update_field(obj, field, value)
    except expected_exc:
        pass
    else:
        raise AssertionError('Expected update to raise %s' % expected_exc)
    finally:
        session = sa.orm.object_session(obj)
        session.rollback()

Example 21

Project: kittystore Source File: model.py
@sa_event.listens_for(Thread, 'before_insert')
def Thread_before_insert(mapper, connection, target):
    """Auto-set the active date from the last email in thread"""
    if target.date_active is not None:
        return
    session = object_session(target)
    last_email_date = session.query(Email.date).order_by(
                            desc(Email.date)).limit(1).scalar()
    if last_email_date:
        target.date_active = last_email_date
    else:
        target.date_active = datetime.datetime.now()

Example 22

Project: indico Source File: users.py
@listens_for(User._primary_email, 'set')
@listens_for(User._secondary_emails, 'append')
@listens_for(User._secondary_emails, 'remove')
def _user_email_changed(target, value, *unused):
    # all_emails is out of sync when changing the emails
    sess = object_session(target)
    if sess is not None:
        sess.expire(target, ['_all_emails'])

Example 23

Project: iktomi Source File: replication.py
def reflect(source, model, cache=None):
    '''Finds an object of class `model` with the same identifier as the
    `source` object'''
    if source is None:
        return None
    if cache and source in cache:
        return cache[source]
    db = object_session(source)
    ident = identity_key(instance=source)[1]
    assert ident is not None
    return db.query(model).get(ident)

Example 24

Project: Camelot Source File: entity_admin.py
Function: expunge
    @model_function
    def expunge(self, entity_instance):
        """Expunge the entity from the session"""
        session = orm.object_session( entity_instance )
        if session:
            objects_to_expunge = set([entity_instance])
            self._expand_compounding_objects( objects_to_expunge )
            for obj in objects_to_expunge:
                if obj in session:
                    session.expunge( obj )

Example 25

Project: kittystore Source File: model.py
Function: get_votes_in_list
    def get_votes_in_list(self, list_name):
        session = object_session(self)
        def getvotes():
            req = session.query(Vote).filter(Vote.list_name == list_name)
            likes = req.filter(Vote.value == 1).count()
            dislikes = req.filter(Vote.value == -1).count()
            return likes, dislikes # TODO: optimize with a Union statement?
        cache_key = str("user:%s:list:%s:votes" % (self.id.int, list_name))
        return session.cache.get_or_create(cache_key, getvotes)

Example 26

Project: Camelot Source File: __init__.py
Function: transaction
def transaction( original_function ):
    """Decorator to make methods transactional with regard to the session
    of the object on which they are called"""
    
    @functools.wraps( original_function )
    def decorated_function( self, *args, **kwargs ):
        session = orm.object_session( self )
        with session.begin():
            return original_function( self, *args, **kwargs )
    
    return decorated_function

Example 27

Project: Camelot Source File: entity_validator.py
Function: validate_object
    def validate_object( self, obj ):
        """:return: list of messages explaining invalid data
        empty list if object is valid
        """
        session = orm.object_session( obj )
        if session == None:
            return []
        if obj in session.deleted:
            return []
        return super( EntityValidator, self ).validate_object( obj )

Example 28

Project: kittystore Source File: model.py
Function: dislikes
    @property
    def dislikes(self):
        session = object_session(self)
        return session.cache.get_or_create(
            str("list:%s:email:%s:dislikes" % (self.list_name, self.message_id)),
            lambda: self._get_votes_query().filter(Vote.value == -1).count()
            )

Example 29

Project: Camelot Source File: authentication.py
def update_last_login():
    """Update the last login of the current person to now"""
    authentication = get_current_authentication()
    authentication.last_login = datetime.datetime.now()
    session = orm.object_session( authentication )
    if session:
        session.flush()

Example 30

Project: CouchPotatoV1 Source File: dynamic.py
Function: session
    def __session(self):
        sess = object_session(self.instance)
        if sess is not None and self.autoflush and sess.autoflush \
            and self.instance in sess:
            sess.flush()
        if not has_identity(self.instance):
            return None
        else:
            return sess

Example 31

Project: Camelot Source File: party.py
    def _set_address_field( self, name, value ):
        if not self.addresses:
            address = PartyAddress()
            self.addresses.append( address )
        address = self.addresses[0]
        setattr( address, name, value )
        if address.street1==None and address.street2==None and address.city==None:
            session = orm.object_session( address )
            if address in session.new:
                session.expunge( address )
                self.addresses.remove( address )
            else:
                session.delete( address )

Example 32

Project: kittystore Source File: model.py
    def _get_participants(self):
        """Email senders in this thread"""
        session = object_session(self)
        return session.query(Sender).join(Email).filter(and_(
                    Email.list_name == self.list_name,
                    Email.thread_id == self.thread_id,
                )).distinct()

Example 33

Project: sqlalchemy-continuum Source File: fetcher.py
Function: index
    def index(self, obj):
        """
        Return the index of this version in the version history.
        """
        session = sa.orm.object_session(obj)
        return session.execute(self._index_query(obj)).fetchone()[0]

Example 34

Project: bauble.classic Source File: __init__.py
    def __init__(self, species, for_labels=False):
        super(SpeciesABCDAdapter, self).__init__(species)

        # hold on to the accession so it doesn't get cleaned up and closed
        self.session = object_session(species)
        self.for_labels = for_labels
        self.species = species
        self._date_format = prefs.prefs[prefs.date_format_pref]

Example 35

Project: sqlalchemy-continuum Source File: fetcher.py
    def next_query(self, obj):
        """
        Returns the query that fetches the next version relative to this
        version in the version history.
        """
        session = sa.orm.object_session(obj)

        return (
            session.query(obj.__class__)
            .filter(
                sa.and_(
                    getattr(obj.__class__, tx_column_name(obj))
                    ==
                    getattr(obj, end_tx_column_name(obj)),
                    *parent_criteria(obj)
                )
            )
        )

Example 36

Project: kittystore Source File: model.py
Function: set_category
    def _set_category(self, name):
        if not name:
            self.category_id = None
            return
        session = object_session(self)
        try:
            category = session.query(Category).filter_by(name=name).one()
        except NoResultFound:
            category = Category(name=name)
            session.add(category)
        self.category_id = category.id

Example 37

Project: sqlalchemy-continuum Source File: manager.py
def tracked_operation(func):
    @wraps(func)
    def wrapper(self, mapper, connection, target):
        if not is_versioned(target):
            return
        session = object_session(target)
        conn = session.connection()
        try:
            uow = self.units_of_work[conn]
        except KeyError:
            uow = self.units_of_work[conn.engine]
        return func(self, uow, target)
    return wrapper

Example 38

Project: formalchemy Source File: tables.py
    def bind(self, instances, session=None, data=None, request=None):
        """bind to instances"""
        _validate_iterable(instances)
        if not session:
            i = iter(instances)
            try:
                instance = next(i)
            except StopIteration:
                pass
            else:
                from sqlalchemy.orm import object_session
                session = object_session(instance)
        mr = FieldSet.bind(self, self.model, session, data, request)
        mr.rows = instances
        mr._request = request
        return mr

Example 39

Project: sqlalchemy-continuum Source File: relationship_builder.py
Function: query
    def query(self, obj):
        session = sa.orm.object_session(obj)
        return (
            session.query(self.remote_cls)
            .filter(
                self.criteria(obj)
            )
        )

Example 40

Project: kittystore Source File: model.py
Function: subject
    @property
    def subject(self):
        session = object_session(self)
        return session.cache.get_or_create(
            str("list:%s:thread:%s:subject"
                % (self.list_name, self.thread_id)),
            lambda: self.starting_email.subject)

Example 41

Project: sqlalchemy-i18n Source File: translatable.py
Function: fetch
    def fetch(self, locale):
        session = sa.orm.object_session(self.obj)
        # If the object has no identity and its not in session or if the object
        # has _translations relationship loaded get the locale object from the
        # relationship.
        if '_translations' not in sa.inspect(self.obj).unloaded or (
            not session or not has_identity(self.obj)
        ):
            return self.obj._translations.get(locale)

        return session.query(self.obj.__translatable__['class']).get(
            sa.inspect(self.obj).identity + (locale, )
        )

Example 42

Project: piecash Source File: sa_extra.py
Function: book
    @property
    def book(self):
        """Return the gnc book holding the object
        """
        s = object_session(self)
        return s and s.book

Example 43

Project: sqlalchemy-utils Source File: asserts.py
def _expect_successful_update(obj, field, value, reraise_exc):
    try:
        _update_field(obj, field, value)
    except (reraise_exc) as e:
        session = sa.orm.object_session(obj)
        session.rollback()
        assert False, str(e)

Example 44

Project: kittystore Source File: model.py
Function: dislikes
    @property
    def dislikes(self):
        session = object_session(self)
        return session.cache.get_or_create(
            str("list:%s:thread:%s:dislikes"
                % (self.list_name, self.thread_id)),
            lambda: self._getvotes().filter(Vote.value == -1).count()
            )

Example 45

Project: kittystore Source File: model.py
Function: recent_threads_count
    @property
    def recent_threads_count(self):
        begin_date, end_date = self.get_recent_dates()
        session = object_session(self)
        return session.cache.get_or_create(
            str("list:%s:recent_threads_count" % self.name),
            lambda: get_threads_between(session, self.name,
                                        begin_date, end_date).count(),
            86400)

Example 46

Project: piecash Source File: kvp.py
Function: remove_slot
@event.listens_for(SlotFrame.slots, 'remove')
def remove_slot(target, value, initiator):
    s = object_session(value)
    if value in s.new:
        s.expunge(value)
    else:
        s.delete(value)

Example 47

Project: piecash Source File: _declbase.py
Function: declare_last
    @classmethod
    def __declare_last__(cls):
        # do not do it on the DeclarativeBaseGuid as it is an abstract class
        if cls == DeclarativeBaseGuid:
            return

        # assign id of slot when associating to object
        @event.listens_for(cls.slots, "remove")
        def my_append_listener_slots(target, value, initiator):
            s = object_session(value)
            if s:
                if value in s.new:
                    s.expunge(value)
                else:
                    s.delete(value)

Example 48

Project: iktomi Source File: replication.py
Function: replicate
def replicate(source, model, cache=None):
    '''Replicates the `source` object to `model` class and returns its
    reflection.'''
    target = replicate_no_merge(source, model, cache=cache)
    if target is not None:
        db = object_session(source)
        target = db.merge(target)
    return target

Example 49

Project: kittystore Source File: model.py
Function: likes
    @property
    def likes(self):
        session = object_session(self)
        return session.cache.get_or_create(
            str("list:%s:email:%s:likes" % (self.list_name, self.message_id)),
            lambda: self._get_votes_query().filter(Vote.value == 1).count()
            )

Example 50

Project: Camelot Source File: entity.py
Function: init
    def __init__( self, *args, **kwargs ): 
        _declarative_constructor( self, *args, **kwargs )
	# due to cascading rules and a constructor argument, the object might
	# allready be in a session
	if orm.object_session( self ) == None:
	    Session().add( self ) 
See More Examples - Go to Next Page
Page 1 Selected Page 2