sqlalchemy.orm.session.Session.object_session

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

32 Examples 7

Example 1

Project: sqlalchemy_mptt Source File: mixins.py
    def move_inside(self, parent_id):
        """ Moving one node of tree inside another

        For example see:

        * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_function`
        * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_to_the_same_parent_function`
        """  # noqa
        session = Session.object_session(self)
        self.parent_id = parent_id
        self.mptt_move_inside = parent_id
        session.add(self)

Example 2

Project: sqlalchemy_mptt Source File: mixins.py
    def move_after(self, node_id):
        """ Moving one node of tree after another

        For example see :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_after_function`
        """  # noqa
        session = Session.object_session(self)
        self.parent_id = self.parent_id
        self.mptt_move_after = node_id
        session.add(self)

Example 3

Project: sqlalchemy_mptt Source File: mixins.py
    def move_before(self, node_id):
        """ Moving one node of tree before another

        For example see:

        * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_before_function`
        * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_before_to_other_tree`
        * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_before_to_top_level`
        """  # noqa
        session = Session.object_session(self)
        table = _get_tree_table(self.__mapper__)
        pk = getattr(table.c, self.get_pk_column().name)
        node = session.query(table).filter(pk == node_id).one()
        self.parent_id = node.parent_id
        self.mptt_move_before = node_id
        session.add(self)

Example 4

Project: sqlalchemy_mptt Source File: mixins.py
    def leftsibling_in_level(self):
        """ Node to the left of the current node at the same level

        For example see :mod:`sqlalchemy_mptt.tests.cases.get_tree.test_leftsibling_in_level`
        """  # noqa
        table = _get_tree_table(self.__mapper__)
        session = Session.object_session(self)
        current_lvl_nodes = session.query(table)\
            .filter_by(level=self.level).filter_by(tree_id=self.tree_id)\
            .filter(table.c.lft < self.left).order_by(table.c.lft).all()
        if current_lvl_nodes:
            return current_lvl_nodes[-1]
        return None

Example 5

Project: sqlalchemy-imageattach Source File: entity.py
Function: non_zero
    def __nonzero__(self):
        session = Session.object_session(self.instance)
        if session is None:
            return bool(self.count())
        for v, in session.query(exists(self.as_scalar())):
            return bool(v)
        return False

Example 6

Project: nowin_core Source File: tables.py
Function: active
    @property
    def active(self):
        """Return is this account active"""
        session = Session.object_session(self)
        verfication = session.query(Verification).\
            filter_by(user=self, passed=True).first()
        return verfication is not None and self.enable

Example 7

Project: nowin_core Source File: tables.py
Function: follower_count
    @property
    def follower_count(self):
        """Get count of follower

        """
        session = Session.object_session(self)
        return session.query(Following) \
            .filter_by(target_id=self.user_id) \
            .count()

Example 8

Project: nowin_core Source File: tables.py
    @property
    def listener_count(self):
        """Return listener count of radio

        """
        from sqlalchemy.sql.functions import sum
        from sqlalchemy.sql.expression import func
        session = Session.object_session(self)
        return session.query(func.ifnull(sum(ProxyConnection.listener), 0)) \
            .filter_by(user_id=self.user_id) \
            .one()

Example 9

Project: Camelot Source File: entity_admin.py
Function: add
    @model_function
    def add( self, obj ):
        """Adds the entity instance to the default session, if it is not
        yet attached to a session"""
        session = Session.object_session( obj )
        if session == None:
            Session().add( obj )

Example 10

Project: Camelot Source File: entity_admin.py
Function: is_persistent
    @model_function
    def is_persistent(self, obj):
        """:return: True if the object has a persisted state, False otherwise"""
        from sqlalchemy.orm.session import Session
        session = Session.object_session( obj )
        if session:
            if obj in session.new:
                return False
            if obj in session.deleted:
                return False
            return True
        return False

Example 11

Project: gertty Source File: db.py
Function: create_change
    def createChange(self, *args, **kw):
        session = Session.object_session(self)
        args = [self] + list(args)
        c = Change(*args, **kw)
        self.changes.append(c)
        session.add(c)
        session.flush()
        return c

Example 12

Project: gertty Source File: db.py
Function: create_branch
    def createBranch(self, *args, **kw):
        session = Session.object_session(self)
        args = [self] + list(args)
        b = Branch(*args, **kw)
        self.branches.append(b)
        session.add(b)
        session.flush()
        return b

Example 13

Project: gertty Source File: db.py
Function: add_project
    def addProject(self, project):
        session = Session.object_session(self)
        seq = max([x.sequence for x in self.project_topics] + [0])
        pt = ProjectTopic(project, self, seq+1)
        self.project_topics.append(pt)
        self.projects.append(project)
        session.add(pt)
        session.flush()

Example 14

Project: gertty Source File: db.py
Function: remove_project
    def removeProject(self, project):
        session = Session.object_session(self)
        for pt in self.project_topics:
            if pt.project_key == project.key:
                self.project_topics.remove(pt)
                session.delete(pt)
        self.projects.remove(project)
        session.flush()

Example 15

Project: gertty Source File: db.py
Function: create_revision
    def createRevision(self, *args, **kw):
        session = Session.object_session(self)
        args = [self] + list(args)
        r = Revision(*args, **kw)
        self.revisions.append(r)
        session.add(r)
        session.flush()
        return r

Example 16

Project: gertty Source File: db.py
Function: create_label
    def createLabel(self, *args, **kw):
        session = Session.object_session(self)
        args = [self] + list(args)
        l = Label(*args, **kw)
        self.labels.append(l)
        session.add(l)
        session.flush()
        return l

Example 17

Project: gertty Source File: db.py
Function: createapproval
    def createApproval(self, *args, **kw):
        session = Session.object_session(self)
        args = [self] + list(args)
        l = Approval(*args, **kw)
        self.approvals.append(l)
        session.add(l)
        session.flush()
        return l

Example 18

Project: gertty Source File: db.py
    def createPermittedLabel(self, *args, **kw):
        session = Session.object_session(self)
        args = [self] + list(args)
        l = PermittedLabel(*args, **kw)
        self.permitted_labels.append(l)
        session.add(l)
        session.flush()
        return l

Example 19

Project: gertty Source File: db.py
    def addConflict(self, other):
        session = Session.object_session(self)
        if other in self.conflicts1 or other in self.conflicts2:
            return
        if self in other.conflicts1 or self in other.conflicts2:
            return
        self.conflicts1.append(other)
        session.flush()
        session.expire(other, attribute_names=['conflicts2'])

Example 20

Project: gertty Source File: db.py
    def delConflict(self, other):
        session = Session.object_session(self)
        if other in self.conflicts1:
            self.conflicts1.remove(other)
            session.flush()
            session.expire(other, attribute_names=['conflicts2'])
        if self in other.conflicts1:
            other.conflicts1.remove(self)
            session.flush()
            session.expire(self, attribute_names=['conflicts2'])

Example 21

Project: gertty Source File: db.py
Function: create_message
    def createMessage(self, *args, **kw):
        session = Session.object_session(self)
        args = [self] + list(args)
        m = Message(*args, **kw)
        self.messages.append(m)
        session.add(m)
        session.flush()
        return m

Example 22

Project: gertty Source File: db.py
    def createPendingCherryPick(self, *args, **kw):
        session = Session.object_session(self)
        args = [self] + list(args)
        c = PendingCherryPick(*args, **kw)
        self.pending_cherry_picks.append(c)
        session.add(c)
        session.flush()
        return c

Example 23

Project: gertty Source File: db.py
Function: create_file
    def createFile(self, *args, **kw):
        session = Session.object_session(self)
        args = [self] + list(args)
        f = File(*args, **kw)
        self.files.append(f)
        session.add(f)
        session.flush()
        if hasattr(self, '_file_cache'):
            self._file_cache[f.path] = f
        return f

Example 24

Project: gertty Source File: db.py
Function: create_comment
    def createComment(self, *args, **kw):
        session = Session.object_session(self)
        args = [self] + list(args)
        c = Comment(*args, **kw)
        self.comments.append(c)
        session.add(c)
        session.flush()
        return c

Example 25

Project: nodepool Source File: nodedb.py
Function: state
    @state.setter
    def state(self, state):
        self._state = state
        self.state_time = int(time.time())
        session = Session.object_session(self)
        if session:
            session.commit()

Example 26

Project: sqlalchemy-imageattach Source File: entity.py
Function: open_file
    def open_file(self, store=current_store, use_seek=False):
        """Opens the file-like object which is a context manager
        (that means it can used for :keyword:`with` statement).

        If ``use_seek`` is :const:`True` (though :const:`False` by default)
        it guarentees the returned file-like object is also seekable
        (provides :meth:`~file.seek()` method).

        :param store: the storage which contains image files.
                      :data:`~sqlalchemy_imageattach.context.current_store`
                      by default
        :type store: :class:`~sqlalchemy_imageattach.store.Store`
        :returns: the file-like object of the image, which is a context
                  manager (plus, also seekable only if ``use_seek``
                  is :const:`True`)
        :rtype: :class:`file`,
                :class:`~sqlalchemy_imageattach.file.FileProxy`,
                file-like object

        """
        if not isinstance(store, Store):
            raise TypeError('store must be an instance of '
                            'sqlalchemy_imageattach.store.Store, not ' +
                            repr(store))

        if Session.object_session(self) is None:
            try:
                file = self.file
            except AttributeError:
                raise IOError('no stored original image file')
            return ReusableFileProxy(file)

        return store.open(self, use_seek)

Example 27

Project: sqlalchemy-imageattach Source File: entity.py
    def _original_images(self, **kwargs):
        """A list of the original images.

        :returns: A list of the original images.
        :rtype: :class:`typing.Sequence`\ [:class:`Image`]
        """

        def test(image):
            if not image.original:
                return False
            for filter, value in kwargs.items():
                if getattr(image, filter) != value:
                    return False
            return True

        if Session.object_session(self.instance) is None:
            images = []
            for image, store in self._stored_images:
                if test(image):
                    images.append(image)

            state = instance_state(self.instance)
            try:
                added = state.committed_state[self.attr.key].added_items
            except KeyError:
                pass
            else:
                for image in added:
                    if test(image):
                        images.append(image)
            if self.session:
                for image in self.session.new:
                    if test(image):
                        images.append(image)
        else:
            query = self.filter_by(original=True, **kwargs)
            images = query.all()
        return images

Example 28

Project: sqlalchemy-imageattach Source File: entity.py
    def generate_thumbnail(self, ratio=None, width=None, height=None,
                           filter='undefined', store=current_store,
                           _preprocess_image=None, _postprocess_image=None):
        """Resizes the :attr:`original` (scales up or down) and
        then store the resized thumbnail into the ``store``.

        :param ratio: resize by its ratio.  if it's greater than 1
                      it scales up, and if it's less than 1 it scales
                      down.  exclusive for ``width`` and ``height``
                      parameters
        :type ratio: :class:`numbers.Real`
        :param width: resize by its width.  exclusive for ``ratio``
                      and ``height`` parameters
        :type width: :class:`numbers.Integral`
        :param height: resize by its height.  exclusive for ``ratio``
                       and ``width`` parameters
        :type height: :class:`numbers.Integral`
        :param filter: a filter type to use for resizing.  choose one in
                       :const:`wand.image.FILTER_TYPES`.  default is
                       ``'undefined'`` which means ImageMagick will try
                       to guess best one to use
        :type filter: :class:`str`, :class:`numbers.Integral`
        :param store: the storage to store the resized image file.
                      :data:`~sqlalchemy_imageattach.context.current_store`
                      by default
        :type store: :class:`~sqlalchemy_imageattach.store.Store`
        :param _preprocess_image: internal-use only option for preprocessing
                                  original image before resizing
        :type _preprocess_image:
            :class:`typing.Callable`\ [[:class:`wand.image.Image`],
                                        :class:`wand.image.Image`]
        :param _postprocess_image: internal-use only option for preprocessing
                                   original image before resizing
        :type _postprocess_image:
            :class:`typing.Callable`\ [[:class:`wand.image.Image`],
                                        :class:`wand.image.Image`]
        :returns: the resized thumbnail image.  it might be an already
                  existing image if the same size already exists
        :rtype: :class:`Image`
        :raise IOError: when there's no :attr:`original` image yet

        """
        params = ratio, width, height
        param_count = sum(p is not None for p in params)
        if not param_count:
            raise TypeError('pass an argument ratio, width, or height')
        elif param_count > 1:
            raise TypeError('pass only one argument in ratio, width, or '
                            'height; these parameters are exclusive for '
                            'each other')

        query = self.query
        transient = Session.object_session(query.instance) is None
        state = instance_state(query.instance)
        try:
            added = state.committed_state[query.attr.key].added_items
        except KeyError:
            added = []
        if width is not None:
            if not isinstance(width, numbers.Integral):
                raise TypeError('width must be integer, not ' + repr(width))
            elif width < 1:
                raise ValueError('width must be natural number, not ' +
                                 repr(width))
            # find the same-but-already-generated thumbnail
            for image in added:
                if image.width == width:
                    return image
            if not transient:
                q = query.filter_by(width=width)
                try:
                    return q.one()
                except NoResultFound:
                    pass

            def height(sz):
                return sz[1] * (width / sz[0])
        elif height is not None:
            if not isinstance(height, numbers.Integral):
                raise TypeError('height must be integer, not ' + repr(height))
            elif height < 1:
                raise ValueError('height must be natural number, not ' +
                                 repr(height))
            # find the same-but-already-generated thumbnail
            for image in added:
                if image.height == height:
                    return image
            if not transient:
                q = query.filter_by(height=height)
                try:
                    return q.one()
                except NoResultFound:
                    pass

            def width(sz):
                return sz[0] * (height / sz[1])
        elif ratio is not None:
            if not isinstance(ratio, numbers.Real):
                raise TypeError('ratio must be an instance of numbers.Real, '
                                'not ' + repr(ratio))

            def width(sz):
                return sz[0] * ratio

            def height(sz):
                return sz[1] * ratio
        data = io.BytesIO()
        image = self.require_original()
        with image.open_file(store=store) as f:
            if _preprocess_image is None:
                img = WandImage(file=f)
            else:
                with WandImage(file=f) as img:
                    img = _preprocess_image(img)
            with img:
                if img.mimetype in VECTOR_TYPES:
                    img.format = 'png'
                original_size = img.size
                if callable(width):
                    width = width(original_size)
                if callable(height):
                    height = height(original_size)
                width = int(width)
                height = int(height)
                # find the same-but-already-generated thumbnail
                for image in added:
                    if image.width == width and image.height == height:
                        return image
                if not transient:
                    q = query.filter_by(width=width, height=height)
                    try:
                        return q.one()
                    except NoResultFound:
                        pass
                if len(img.sequence) > 1:
                    img_ctx = img.sequence[0].clone()
                    img_ctx.resize(width, height, filter=filter)
                else:
                    img_ctx = NoopContext(img)
                with img_ctx as single_img:
                    single_img.resize(width, height, filter=filter)
                    if _postprocess_image is None:
                        mimetype = img.mimetype
                        single_img.save(file=data)
                    else:
                        with _postprocess_image(img) as img:
                            mimetype = img.mimetype
                            single_img.save(file=data)
        return self.from_raw_file(data, store,
                                  size=(width, height),
                                  mimetype=mimetype,
                                  original=False)

Example 29

Project: home-assistant Source File: models.py
    def entity_ids(self, point_in_time=None):
        """Return the entity ids that existed in this run.

        Specify point_in_time if you want to know which existed at that point
        in time inside the run.
        """
        from sqlalchemy.orm.session import Session

        session = Session.object_session(self)

        assert session is not None, 'RecorderRuns need to be persisted'

        query = session.query(distinct(States.entity_id)).filter(
            States.last_updated >= self.start)

        if point_in_time is not None:
            query = query.filter(States.last_updated < point_in_time)
        elif self.end is not None:
            query = query.filter(States.last_updated < self.end)

        return [row[0] for row in query]

Example 30

Project: Camelot Source File: entity_admin.py
    @model_function
    def delete(self, entity_instance):
        """Delete an entity instance"""
        session = Session.object_session( entity_instance )
        #
        # new and deleted instances cannot be deleted
        #
        if session:
            if entity_instance in session.new:
                session.expunge(entity_instance)
            elif entity_instance not in session.deleted:
                #
                # only if we know the primary key, we can keep track of its history
                #
                primary_key = self.primary_key( entity_instance )
                if not None in primary_key:
                    # save the state before the update
                    memento = self.get_memento()
                    if memento != None:
                        modifications = entity_to_dict( entity_instance )
                        change = memento_change( model = unicode( self.entity.__name__ ),
                                                 memento_type = 'before_delete',
                                                 primary_key = primary_key,
                                                 previous_attributes = modifications )
                        memento.register_changes( [change] )
                session.delete( entity_instance )
                self.flush( entity_instance )

Example 31

Project: Camelot Source File: entity_admin.py
    @model_function
    def flush(self, entity_instance):
        """Flush the pending changes of this entity instance to the backend"""
        from sqlalchemy.orm.session import Session
        session = Session.object_session( entity_instance )
        if session:
            objects_to_flush = set([entity_instance])
            self._expand_compounding_objects( objects_to_flush )
            #
            # Create a list of changes
            #
            changes = []
            for obj_to_flush in objects_to_flush:
                if obj_to_flush in session.dirty:
                    modifications = {}
                    try:
                        modifications = self.get_modifications( obj_to_flush )
                    except Exception, e:
                        # todo : there seems to be a bug in sqlalchemy that causes the
                        #        get history to fail in some cases
                        logger.error( 'could not get modifications from object', exc_info = e )
                    primary_key = self.primary_key( obj_to_flush )
                    if modifications and (None not in primary_key):
                        change = memento_change( model = unicode( self.entity.__name__ ),
                                                 memento_type = 'before_update',
                                                 primary_key = primary_key,
                                                 previous_attributes = modifications )
                        changes.append( change )
            session.flush( objects_to_flush )
            #
            # If needed, track the changes
            #
            memento = self.get_memento()
            if changes and memento != None:
                memento.register_changes( changes )

Example 32

Project: nodepool Source File: nodedb.py
Function: delete
    def delete(self):
        session = Session.object_session(self)
        session.delete(self)
        session.commit()