sqlalchemy.orm.session.object_session

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

77 Examples 7

Example 1

Project: bauble.classic
Source File: location.py
View license
    def update(self, row):
        '''
        '''
        from bauble.plugins.garden.plant import Plant
        self.widget_set_value('loc_name_data',
                              '<big>%s</big>' % utils.xml_safe(str(row)),
                              markup=True)
        session = object_session(row)
        nplants = session.query(Plant).filter_by(location_id=row.id).count()
        self.widget_set_value('loc_nplants_data', nplants)

Example 2

Project: bauble.classic
Source File: family.py
View license
    @property
    def accepted(self):
        'Name that should be used if name of self should be rejected'
        session = object_session(self)
        if not session:
            logger.warn('family:accepted - object not in session')
            return None
        syn = session.query(FamilySynonym).filter(
            FamilySynonym.synonym_id == self.id).first()
        accepted = syn and syn.family
        return accepted

Example 3

Project: bauble.classic
Source File: family.py
View license
    @accepted.setter
    def accepted(self, value):
        'Name that should be used if name of self should be rejected'
        assert isinstance(value, self.__class__)
        if self in value.synonyms:
            return
        # remove any previous `accepted` link
        session = object_session(self)
        if not session:
            logger.warn('family:accepted.setter - object not in session')
            return
        session.query(FamilySynonym).filter(
            FamilySynonym.synonym_id == self.id).delete()
        session.commit()
        value.synonyms.append(self)

Example 4

Project: bauble.classic
Source File: genus.py
View license
    @property
    def accepted(self):
        'Name that should be used if name of self should be rejected'
        session = object_session(self)
        if not session:
            logger.warn('genus:accepted - object not in session')
            return None
        syn = session.query(GenusSynonym).filter(
            GenusSynonym.synonym_id == self.id).first()
        accepted = syn and syn.genus
        return accepted

Example 5

Project: bauble.classic
Source File: genus.py
View license
    @accepted.setter
    def accepted(self, value):
        'Name that should be used if name of self should be rejected'
        assert isinstance(value, self.__class__)
        if self in value.synonyms:
            return
        # remove any previous `accepted` link
        session = object_session(self)
        if not session:
            logger.warn('genus:accepted.setter - object not in session')
            return
        session.query(GenusSynonym).filter(
            GenusSynonym.synonym_id == self.id).delete()
        session.commit()
        value.synonyms.append(self)

Example 6

Project: bauble.classic
Source File: species_model.py
View license
    @property
    def accepted(self):
        'Name that should be used if name of self should be rejected'
        from sqlalchemy.orm.session import object_session
        session = object_session(self)
        if not session:
            logger.warn('species:accepted - object not in session')
            return None
        syn = session.query(SpeciesSynonym).filter(
            SpeciesSynonym.synonym_id == self.id).first()
        accepted = syn and syn.species
        return accepted

Example 7

Project: bauble.classic
Source File: species_model.py
View license
    @accepted.setter
    def accepted(self, value):
        'Name that should be used if name of self should be rejected'
        logger.debug("Accepted taxon: %s %s" % (type(value), value))
        assert isinstance(value, self.__class__)
        if self in value.synonyms:
            return
        # remove any previous `accepted` link
        from sqlalchemy.orm.session import object_session
        session = object_session(self)
        if not session:
            logger.warn('species:accepted.setter - object not in session')
            return
        session.query(SpeciesSynonym).filter(
            SpeciesSynonym.synonym_id == self.id).delete()
        session.commit()
        value.synonyms.append(self)

Example 8

Project: bauble.classic
Source File: __init__.py
View license
    def get_tagged_objects(self):
        """
        Return all object tagged with tag.

        """
        session = object_session(self)

        # filter out any None values from the query which can happen if
        # you tag something and then delete it from the datebase

        # TODO: the missing tagged objects should probably be removed from
        # the database
        r = [session.query(mapper).filter_by(id=obj_id).first()
             for mapper, obj_id in _get_tagged_object_pairs(self)]
        r = [i for i in r if i is not None]
        return r

Example 9

Project: bauble.classic
Source File: __init__.py
View license
    @classmethod
    def attached_to(cls, obj):
        """return the list of tags attached to obj

        this is a class method, so more classes can invoke it.
        """
        session = object_session(obj)
        if not session:
            return []
        modname = type(obj).__module__
        clsname = type(obj).__name__
        full_cls_name = '%s.%s' % (modname, clsname)
        qto = session.query(TaggedObj).filter(
            TaggedObj.obj_class == full_cls_name,
            TaggedObj.obj_id == obj.id)
        return [i.tag for i in qto.all()]

Example 10

Project: iktomi
Source File: files.py
View license
    def _2persistent(self, target, transient):
        session = object_session(target)
        persistent_name = getattr(target, self.prop.attribute_name).decode('utf-8')
        attr = getattr(type(target), self.prop.key)
        file_manager = session.find_file_manager(attr)
        persistent = file_manager.get_persistent(persistent_name,
                                                 self.prop.persistent_cls)

        file_attr = getattr(target.__class__, self.prop.key)
        file_manager = session.find_file_manager(file_attr)

        return file_manager.store(transient, persistent)

Example 11

Project: iktomi
Source File: files.py
View license
    def before_update(self, mapper, connection, target):
        changes = self._get_history(target)
        if not (changes.deleted or changes.added):
            return
        if changes.deleted:
            old_name = self._get_file_name_to_delete(target, changes)
            if old_name:
                session = object_session(target)

                file_attr = getattr(target.__class__, self.prop.key)
                file_manager = session.find_file_manager(file_attr)

                old = file_manager.get_persistent(old_name,
                                                  self.prop.persistent_cls)
                self._remove_file(old.path)
        self._store_transient(target)

Example 12

Project: iktomi
Source File: files.py
View license
    def after_delete(self, mapper, connection, target):
        changes = self._get_history(target)
        old_name = self._get_file_name_to_delete(target, changes)
        old_name = old_name or getattr(target, self.prop.attribute_name)
        if old_name is not None:
            old_name = old_name.decode('utf-8')
            session = object_session(target)

            file_attr = getattr(target.__class__, self.prop.key)
            file_manager = session.find_file_manager(file_attr)

            old = file_manager.get_persistent(old_name,
                                              self.prop.persistent_cls)
            self._remove_file(old.path)

Example 13

Project: pokedex
Source File: multilang.py
View license
def _getset_factory_factory(column_name, string_getter):
    """Hello!  I am a factory for creating getset_factory functions for SQLA.
    I exist to avoid the closure-in-a-loop problem.
    """
    def getset_factory(underlying_type, instance):
        def getter(translations):
            if translations is None:
                return None
            text = getattr(translations, column_name)
            if text is None:
                return text
            session = object_session(translations)
            language = translations.local_language
            return string_getter(text, session, language)
        def setter(translations, value):
            # The string must be set on the Translation directly.
            raise AttributeError("Cannot set %s" % column_name)
        return getter, setter
    return getset_factory

Example 14

Project: ghini.desktop
Source File: location.py
View license
    def update(self, row):
        '''
        '''
        self.current_obj = row
        from bauble.plugins.garden.plant import Plant
        self.widget_set_value('loc_name_data',
                              '<big>%s</big>' % utils.xml_safe(str(row)),
                              markup=True)
        session = object_session(row)
        nplants = session.query(Plant).filter_by(location_id=row.id).count()
        self.widget_set_value('loc_nplants_data', nplants)

Example 15

Project: ghini.desktop
Source File: family.py
View license
    @property
    def accepted(self):
        'Name that should be used if name of self should be rejected'
        session = object_session(self)
        if not session:
            logger.warn('family:accepted - object not in session')
            return None
        syn = session.query(FamilySynonym).filter(
            FamilySynonym.synonym_id == self.id).first()
        accepted = syn and syn.family
        return accepted

Example 16

Project: ghini.desktop
Source File: family.py
View license
    @accepted.setter
    def accepted(self, value):
        'Name that should be used if name of self should be rejected'
        assert isinstance(value, self.__class__)
        if self in value.synonyms:
            return
        # remove any previous `accepted` link
        session = object_session(self)
        if not session:
            logger.warn('family:accepted.setter - object not in session')
            return
        session.query(FamilySynonym).filter(
            FamilySynonym.synonym_id == self.id).delete()
        session.commit()
        value.synonyms.append(self)

Example 17

Project: ghini.desktop
Source File: genus.py
View license
    @property
    def accepted(self):
        'Name that should be used if name of self should be rejected'
        session = object_session(self)
        if not session:
            logger.warn('genus:accepted - object not in session')
            return None
        syn = session.query(GenusSynonym).filter(
            GenusSynonym.synonym_id == self.id).first()
        accepted = syn and syn.genus
        return accepted

Example 18

Project: ghini.desktop
Source File: genus.py
View license
    @accepted.setter
    def accepted(self, value):
        'Name that should be used if name of self should be rejected'
        assert isinstance(value, self.__class__)
        if self in value.synonyms:
            return
        # remove any previous `accepted` link
        session = object_session(self)
        if not session:
            logger.warn('genus:accepted.setter - object not in session')
            return
        session.query(GenusSynonym).filter(
            GenusSynonym.synonym_id == self.id).delete()
        session.commit()
        value.synonyms.append(self)

Example 19

Project: ghini.desktop
Source File: species_model.py
View license
    @property
    def accepted(self):
        'Name that should be used if name of self should be rejected'
        from sqlalchemy.orm.session import object_session
        session = object_session(self)
        if not session:
            logger.warn('species:accepted - object not in session')
            return None
        syn = session.query(SpeciesSynonym).filter(
            SpeciesSynonym.synonym_id == self.id).first()
        accepted = syn and syn.species
        return accepted

Example 20

Project: ghini.desktop
Source File: species_model.py
View license
    @accepted.setter
    def accepted(self, value):
        'Name that should be used if name of self should be rejected'
        logger.debug("Accepted taxon: %s %s" % (type(value), value))
        assert isinstance(value, self.__class__)
        if self in value.synonyms:
            return
        # remove any previous `accepted` link
        from sqlalchemy.orm.session import object_session
        session = object_session(self)
        if not session:
            logger.warn('species:accepted.setter - object not in session')
            return
        session.query(SpeciesSynonym).filter(
            SpeciesSynonym.synonym_id == self.id).delete()
        session.commit()
        value.synonyms.append(self)

Example 21

Project: ghini.desktop
Source File: __init__.py
View license
    def get_tagged_objects(self):
        """
        Return all object tagged with tag.

        """
        session = object_session(self)

        # filter out any None values from the query which can happen if
        # you tag something and then delete it from the datebase

        # TODO: the missing tagged objects should probably be removed from
        # the database
        r = [session.query(mapper).filter_by(id=obj_id).first()
             for mapper, obj_id in _get_tagged_object_pairs(self)]
        r = [i for i in r if i is not None]
        return r

Example 22

Project: ghini.desktop
Source File: __init__.py
View license
    @classmethod
    def attached_to(cls, obj):
        """return the list of tags attached to obj

        this is a class method, so more classes can invoke it.
        """
        session = object_session(obj)
        if not session:
            return []
        modname = type(obj).__module__
        clsname = type(obj).__name__
        full_cls_name = '%s.%s' % (modname, clsname)
        qto = session.query(TaggedObj).filter(
            TaggedObj.obj_class == full_cls_name,
            TaggedObj.obj_id == obj.id)
        return [i.tag for i in qto.all()]

Example 23

Project: indico
Source File: surveys.py
View license
@listens_for(Survey.items, 'append')
@listens_for(Survey.items, 'remove')
def _items_modified(target, value, *unused):
    sess = object_session(target)
    if sess is not None and inspect(target).persistent:
        sess.expire(target, ['questions', 'sections'])

Example 24

Project: sqlalchemy-i18n
Source File: manager.py
View license
    def create_missing_locales(self, obj):
        """
        Creates empty locale objects for given SQLAlchemy declarative object.

        :param model: SQLAlchemy declarative model object
        """
        session = sa.orm.session.object_session(obj)
        for locale in self.option(obj, 'locales'):
            if obj.translations[locale] is None:
                class_ = obj.__translatable__['class']
                obj.translations[locale] = class_(
                    translation_parent=obj,
                    locale=locale
                )
            self.set_not_nullables_to_empty_strings(locale, obj)
            session.add(obj)

Example 25

Project: sqlalchemy-i18n
Source File: manager.py
View license
    def create_missing_locales(self, obj):
        """
        Creates empty locale objects for given SQLAlchemy declarative object.

        :param model: SQLAlchemy declarative model object
        """
        session = sa.orm.session.object_session(obj)
        for locale in self.option(obj, 'locales'):
            if obj.translations[locale] is None:
                class_ = obj.__translatable__['class']
                obj.translations[locale] = class_(
                    translation_parent=obj,
                    locale=locale
                )
            self.set_not_nullables_to_empty_strings(locale, obj)
            session.add(obj)

Example 26

Project: webcheck
Source File: db.py
View license
    def _get_child(self, url):
        """Get a link object for the specified URL."""
        # get the session
        session = object_session(self)
        # normalise the URL, removing the fragment from the URL
        url, fragment = urlparse.urldefrag(normalizeurl(url))
        # try to find the link
        instance = self.get_or_create(session, url)
        # we may have discovered a shorter path
        instance.depth = min(instance.depth, self.depth + 1) or self.depth + 1
        # mark that we were looking for an anchor/fragment
        if fragment:
            instance.add_reqanchor(self, fragment)
        # return the link
        return instance

Example 27

Project: webcheck
Source File: db.py
View license
    def add_redirect(self, url):
        """Indicate that this link redirects to the specified url."""
        session = object_session(self)
        url = self.clean_url(url)
        # check for (possibly indirect) redirects to self
        for link in session.query(Link).filter_by(url=url):
            if link.follow_link() == self:
                link.add_linkproblem('redirects back to source: %s' % self.url)
                self.add_linkproblem('redirects back to source: %s' % link.url)
                return
        # figure out depth (how can [self.redirectdepth] ever by non-zero?)
        self.redirectdepth = max([self.redirectdepth] +
                                 [x.redirectdepth for x in self.parents]) + 1
        # check depth
        if self.redirectdepth >= config.REDIRECT_DEPTH:
            self.add_linkproblem('too many redirects (%d)' % self.redirectdepth)
            return
        # add child
        self.add_child(url)

Example 28

Project: webcheck
Source File: db.py
View license
    @property
    def parents(self):
        session = object_session(self)
        parent_ids = union(session.query(children.c.parent_id).filter(children.c.child_id == self.id),
                           session.query(embedded.c.parent_id).filter(embedded.c.child_id == self.id))
        return session.query(Link).filter(Link.id == parent_ids.c.children_parent_id)

Example 29

Project: webcheck
Source File: db.py
View license
    def _get_child(self, url):
        """Get a link object for the specified URL."""
        # get the session
        session = object_session(self)
        # normalise the URL, removing the fragment from the URL
        url, fragment = urlparse.urldefrag(normalizeurl(url))
        # try to find the link
        instance = self.get_or_create(session, url)
        # we may have discovered a shorter path
        instance.depth = min(instance.depth, self.depth + 1) or self.depth + 1
        # mark that we were looking for an anchor/fragment
        if fragment:
            instance.add_reqanchor(self, fragment)
        # return the link
        return instance

Example 30

Project: webcheck
Source File: db.py
View license
    def add_redirect(self, url):
        """Indicate that this link redirects to the specified url."""
        session = object_session(self)
        url = self.clean_url(url)
        # check for (possibly indirect) redirects to self
        for link in session.query(Link).filter_by(url=url):
            if link.follow_link() == self:
                link.add_linkproblem('redirects back to source: %s' % self.url)
                self.add_linkproblem('redirects back to source: %s' % link.url)
                return
        # figure out depth (how can [self.redirectdepth] ever by non-zero?)
        self.redirectdepth = max([self.redirectdepth] +
                                 [x.redirectdepth for x in self.parents]) + 1
        # check depth
        if self.redirectdepth >= config.REDIRECT_DEPTH:
            self.add_linkproblem('too many redirects (%d)' % self.redirectdepth)
            return
        # add child
        self.add_child(url)

Example 31

Project: webcheck
Source File: db.py
View license
    @property
    def parents(self):
        session = object_session(self)
        parent_ids = union(session.query(children.c.parent_id).filter(children.c.child_id == self.id),
                           session.query(embedded.c.parent_id).filter(embedded.c.child_id == self.id))
        return session.query(Link).filter(Link.id == parent_ids.c.children_parent_id)

Example 32

Project: gnocchi
Source File: sqlalchemy_base.py
View license
    def get_metric(self, metric_name):
        m = super(Resource, self).get_metric(metric_name)
        if m:
            if sqlalchemy.orm.session.object_session(self):
                # NOTE(jd) The resource is already loaded so that should not
                # trigger a SELECT
                m.resource
            return m

Example 33

Project: bauble.classic
Source File: location.py
View license
    def __init__(self, model, view):
        '''
        model: should be an instance of class Accession
        view: should be an instance of AccessionEditorView
        '''
        GenericEditorPresenter.__init__(self, model, view)
        self.session = object_session(model)
        self._dirty = False

        # initialize widgets
        self.refresh_view()  # put model values in view

        # connect signals
        self.assign_simple_handler('loc_name_entry', 'name',
                                   UnicodeOrNoneValidator())
        self.assign_simple_handler('loc_code_entry', 'code',
                                   UnicodeOrNoneValidator())
        self.assign_simple_handler('loc_desc_textview', 'description',
                                   UnicodeOrNoneValidator())
        self.refresh_sensitivity()
        if self.model not in self.session.new:
            self.view.widgets.loc_ok_and_add_button.set_sensitive(True)

        # the merger danger zone
        self.merger_candidate = None

        def on_location_select(location):
            logger.debug('merger candidate: %s' % location)
            self.merger_candidate = location

        from bauble.plugins.garden import init_location_comboentry
        init_location_comboentry(self, self.view.widgets.loc_merge_comboentry,
                                 on_location_select)
        self.view.connect('loc_merge_button', 'clicked',
                          self.on_loc_merge_button_clicked)

Example 34

Project: bauble.classic
Source File: propagation.py
View license
    def __init__(self, model, view):
        '''
        :param model: an instance of class Propagation
        :param view: an instance of PropagationEditorView
        '''
        super(PropagationPresenter, self).__init__(model, view)
        self.session = object_session(model)

        # initialize the propagation type combo and set the initial value
        self.view.connect('prop_type_combo', 'changed',
                          self.on_prop_type_changed)
        if self.model.prop_type:
            self.view.widget_set_value('prop_type_combo', self.model.prop_type)

        self._cutting_presenter = CuttingPresenter(self, self.model, self.view,
                                                   self.session)
        self._seed_presenter = SeedPresenter(self, self.model, self.view,
                                             self.session)

        if not self.model.prop_type:
            view.widgets.prop_details_box.props.visible = False

        if self.model.date:
            format = prefs.prefs[prefs.date_format_pref]
            date = self.model.date.strftime(format)
            self.view.widget_set_value(self.view.widgets.prop_date_entry, date)
        else:
            self.view.widget_set_value(self.view.widgets.prop_date_entry,
                                       utils.today_str())

        self.view.widget_set_value(self.view.widgets.notes_textview,
                                   self.model.notes)

        self._dirty = False
        utils.setup_date_button(self.view, 'prop_date_entry',
                                'prop_date_button')
        self.assign_simple_handler('prop_date_entry', 'date',
                                   editor.DateValidator())
        self.assign_simple_handler('notes_textview', 'notes',
                                   editor.UnicodeOrNoneValidator())

        def on_expanded(*args):
            if self.model.prop_type == u'Other':
                # i don't really understand why setting the expanded
                # property to false here cause the notes_expander to
                # always stay expanded but it works
                self.view.widgets.notes_expander.props.expanded = False
        self.view.connect('notes_expander', 'activate', on_expanded)

Example 35

Project: bauble.classic
Source File: propagation.py
View license
    def __init__(self, model, parent=None):
        '''
        :param prop_parent: an instance with a propagation relation
        :param model: Propagation instance
        :param parent: the parent widget
        '''
        # the view and presenter are created in self.start()
        self.view = None
        self.presenter = None
        super(PropagationEditor, self).__init__(model, parent)
        # if mode already has a session then use it, this is unique to
        # the PropagationEditor because so far it is the only editor
        # that dependent on a parent editor and the parent editor's
        # model and session
        sess = object_session(model)
        if sess:
            self.session.close()
            self.session = sess
            self.model = model

        if not parent and bauble.gui:
            parent = bauble.gui.window
        self.parent = parent

        view = PropagationEditorView(parent=self.parent)
        self.presenter = PropagationEditorPresenter(self.model, view)

        # add quick response keys
        self.attach_response(view.get_window(), gtk.RESPONSE_OK, 'Return',
                             gtk.gdk.CONTROL_MASK)
        self.attach_response(view.get_window(), self.RESPONSE_OK_AND_ADD, 'k',
                             gtk.gdk.CONTROL_MASK)
        self.attach_response(view.get_window(), self.RESPONSE_NEXT, 'n',
                             gtk.gdk.CONTROL_MASK)

Example 36

Project: bauble.classic
Source File: family.py
View license
def remove_callback(families):
    """
    The callback function to remove a family from the family context menu.
    """
    family = families[0]
    from bauble.plugins.plants.genus import Genus
    session = object_session(family)
    ngen = session.query(Genus).filter_by(family_id=family.id).count()
    safe_str = utils.xml_safe(str(family))
    if ngen > 0:
        msg = _('The family <i>%(family)s</i> has %(num_genera)s genera.  Are '
                'you sure you want to remove it?') % dict(family=safe_str,
                                                          num_genera=ngen)
    else:
        msg = _("Are you sure you want to remove the family <i>%s</i>?") \
            % safe_str
    if not utils.yes_no_dialog(msg):
        return
    try:
        obj = session.query(Family).get(family.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe(e)
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
    finally:
        session.close()
    return True

Example 37

Project: bauble.classic
Source File: family.py
View license
    def __init__(self, model, view):
        '''
        :param model: should be an instance of class Family
        :param view: should be an instance of FamilyEditorView
        '''
        super(FamilyEditorPresenter, self).__init__(model, view)
        self.session = object_session(model)

        # initialize widgets
        self.init_enum_combo('fam_qualifier_combo', 'qualifier')
        self.synonyms_presenter = SynonymsPresenter(self)
        self.refresh_view()  # put model values in view

        # connect signals
        self.assign_simple_handler('fam_family_entry', 'family',
                                   editor.UnicodeOrNoneValidator())
        self.assign_simple_handler('fam_qualifier_combo', 'qualifier',
                                   editor.UnicodeOrEmptyValidator())

        notes_parent = self.view.widgets.notes_parent_box
        notes_parent.foreach(notes_parent.remove)
        self.notes_presenter = \
            editor.NotesPresenter(self, 'notes', notes_parent)

        if self.model not in self.session.new:
            self.view.widgets.fam_ok_and_add_button.set_sensitive(True)

        # for each widget register a signal handler to be notified when the
        # value in the widget changes, that way we can do things like sensitize
        # the ok button
        self._dirty = False

Example 38

Project: bauble.classic
Source File: family.py
View license
    def update(self, row):
        '''
        update the expander

        :param row: the row to get the values from
        '''
        self.current_obj = row
        self.widget_set_value('fam_name_data', '<big>%s</big>' % row,
                              markup=True)
        session = object_session(row)
        # get the number of genera
        ngen = session.query(Genus).filter_by(family_id=row.id).count()
        self.widget_set_value('fam_ngen_data', ngen)

        # get the number of species
        nsp = (session.query(Species).join('genus').
               filter_by(family_id=row.id).count())
        if nsp == 0:
            self.widget_set_value('fam_nsp_data', 0)
        else:
            ngen_in_sp = (session.query(Species.genus_id).
                          join('genus', 'family').
                          filter_by(id=row.id).distinct().count())
            self.widget_set_value('fam_nsp_data', '%s in %s genera'
                                  % (nsp, ngen_in_sp))

        # stop here if no GardenPlugin
        if 'GardenPlugin' not in pluginmgr.plugins:
            return

        # get the number of accessions in the family
        from bauble.plugins.garden.accession import Accession
        from bauble.plugins.garden.plant import Plant

        nacc = (session.query(Accession).
                join('species', 'genus', 'family').
                filter_by(id=row.id).count())
        if nacc == 0:
            self.widget_set_value('fam_nacc_data', nacc)
        else:
            nsp_in_acc = (session.query(Accession.species_id).
                          join('species', 'genus', 'family').
                          filter_by(id=row.id).distinct().count())
            self.widget_set_value('fam_nacc_data', '%s in %s species'
                                  % (nacc, nsp_in_acc))

        # get the number of plants in the family
        nplants = (session.query(Plant).
                   join('accession', 'species', 'genus', 'family').
                   filter_by(id=row.id).count())
        if nplants == 0:
            self.widget_set_value('fam_nplants_data', nplants)
        else:
            nacc_in_plants = session.query(Plant.accession_id).\
                join('accession', 'species', 'genus', 'family').\
                filter_by(id=row.id).distinct().count()
            self.widget_set_value('fam_nplants_data', '%s in %s accessions'
                                  % (nplants, nacc_in_plants))

Example 39

Project: bauble.classic
Source File: genus.py
View license
def remove_callback(genera):
    """
    The callback function to remove a genus from the genus context menu.
    """
    genus = genera[0]
    from bauble.plugins.plants.species_model import Species
    session = object_session(genus)
    nsp = session.query(Species).filter_by(genus_id=genus.id).count()
    safe_str = utils.xml_safe(str(genus))
    if nsp > 0:
        msg = (_('The genus <i>%(genus)s</i> has %(num_species)s species.  '
                 'Are you sure you want to remove it?')
               % dict(genus=safe_str, num_species=nsp))
    else:
        msg = (_("Are you sure you want to remove the genus <i>%s</i>?")
               % safe_str)
    if not utils.yes_no_dialog(msg):
        return
    try:
        obj = session.query(Genus).get(genus.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe(e)
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
    return True

Example 40

Project: bauble.classic
Source File: genus.py
View license
    def __init__(self, model, view):
        '''
        @model: should be an instance of class Genus
        @view: should be an instance of GenusEditorView
        '''
        super(GenusEditorPresenter, self).__init__(model, view)
        self.session = object_session(model)

        # initialize widgets
        self.synonyms_presenter = SynonymsPresenter(self)
        self.refresh_view()  # put model values in view

        # connect signals
        def fam_get_completions(text):
            query = self.session.query(Family)
            return query.filter(Family.family.like('%s%%' % text)).\
                order_by(Family.family)

        def on_select(value):
            for kid in self.view.widgets.message_box_parent.get_children():
                self.view.widgets.remove_parent(kid)
            self.set_model_attr('family', value)
            if not value:
                return
            syn = self.session.query(FamilySynonym).filter(
                FamilySynonym.synonym_id == value.id).first()
            if not syn:
                self.set_model_attr('family', value)
                return
            msg = _('The family <b>%(synonym)s</b> is a synonym of '
                    '<b>%(family)s</b>.\n\nWould you like to choose '
                    '<b>%(family)s</b> instead?') % \
                {'synonym': syn.synonym, 'family': syn.family}
            box = None

            def on_response(button, response):
                self.view.widgets.remove_parent(box)
                box.destroy()
                if response:
                    # populate the completions model on the entry so
                    # when we set the text it will match the
                    # completion and set the value
                    completion = self.view.widgets.gen_family_entry.\
                        get_completion()
                    utils.clear_model(completion)
                    model = gtk.ListStore(object)
                    model.append([syn.family])
                    completion.set_model(model)
                    self.view.widgets.gen_family_entry.\
                        set_text(utils.utf8(syn.family))
                    # the family value should be set properly when the
                    # text is set on the entry but it doesn't hurt to
                    # duplicate it here
                    self.set_model_attr('family', syn.family)

            box = self.view.add_message_box(utils.MESSAGE_BOX_YESNO)
            box.message = msg
            box.on_response = on_response
            box.show()

        self.assign_completions_handler('gen_family_entry',
                                        fam_get_completions,
                                        on_select=on_select)
        self.assign_simple_handler('gen_genus_entry', 'genus',
                                   editor.UnicodeOrNoneValidator())
        self.assign_simple_handler('gen_author_entry', 'author',
                                   editor.UnicodeOrNoneValidator())

        notes_parent = self.view.widgets.notes_parent_box
        notes_parent.foreach(notes_parent.remove)
        self.notes_presenter = \
            editor.NotesPresenter(self, 'notes', notes_parent)

        if self.model not in self.session.new:
            self.view.widgets.gen_ok_and_add_button.set_sensitive(True)

        self._dirty = False

Example 41

Project: bauble.classic
Source File: genus.py
View license
    def update(self, row):
        '''
        update the expander

        :param row: the row to get the values from
        '''
        session = object_session(row)
        self.current_obj = row
        self.widget_set_value('gen_name_data', '<big>%s</big> %s' %
                              (row, utils.xml_safe(unicode(row.author))),
                              markup=True)
        self.widget_set_value('gen_fam_data',
                              (utils.xml_safe(unicode(row.family))))

        # get the number of species
        nsp = (session.query(Species).
               join('genus').
               filter_by(id=row.id).count())
        self.widget_set_value('gen_nsp_data', nsp)

        # stop here if no GardenPlugin
        if 'GardenPlugin' not in pluginmgr.plugins:
            return

        from bauble.plugins.garden.accession import Accession
        from bauble.plugins.garden.plant import Plant

        # get number of accessions
        nacc = (session.query(Accession).
                join('species', 'genus').
                filter_by(id=row.id).count())
        if nacc == 0:
            self.widget_set_value('gen_nacc_data', nacc)
        else:
            nsp_in_acc = (session.query(Accession.species_id).
                          join('species', 'genus').
                          filter_by(id=row.id).distinct().count())
            self.widget_set_value('gen_nacc_data', '%s in %s species'
                                  % (nacc, nsp_in_acc))

        # get the number of plants in the genus
        nplants = (session.query(Plant).
                   join('accession', 'species', 'genus').
                   filter_by(id=row.id).count())
        if nplants == 0:
            self.widget_set_value('gen_nplants_data', nplants)
        else:
            nacc_in_plants = (session.query(Plant.accession_id).
                              join('accession', 'species', 'genus').
                              filter_by(id=row.id).distinct().count())
            self.widget_set_value('gen_nplants_data', '%s in %s accessions'
                                  % (nplants, nacc_in_plants))

Example 42

Project: bauble.classic
Source File: species.py
View license
def remove_callback(values):
    """
    The callback function to remove a species from the species context menu.
    """
    from bauble.plugins.garden.accession import Accession
    species = values[0]
    session = object_session(species)
    if isinstance(species, VernacularName):
        species = species.species
    nacc = session.query(Accession).filter_by(species_id=species.id).count()
    safe_str = utils.xml_safe(str(species))
    if nacc > 0:
        msg = _('The species <i>%(species)s</i> has %(num_accessions)s '
                'accessions.  Are you sure you want remove it?') \
            % dict(species=safe_str, num_accessions=nacc)
    else:
        msg = _("Are you sure you want to remove the species <i>%s</i>?") \
            % safe_str
    if not utils.yes_no_dialog(msg):
        return
    try:
        obj = session.query(Species).get(species.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe(e)
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
    return True

Example 43

Project: bauble.classic
Source File: species.py
View license
    def update(self, row):
        '''
        update the expander

        :param row: the row to get thevalues from
        '''
        syn_box = self.widgets.sp_synonyms_box
        # remove old labels
        syn_box.foreach(syn_box.remove)
        logger.debug(row.synonyms)
        session = object_session(row)
        syn = session.query(SpeciesSynonym).filter(
            SpeciesSynonym.synonym_id == row.id).first()
        accepted = syn and syn.species
        logger.debug("species %s is synonym of %s and has synonyms %s" %
                     (row, accepted, row.synonyms))
        self.set_label(_("Synonyms"))  # reset default value
        on_label_clicked = lambda l, e, syn: select_in_search_results(syn)
        if accepted is not None:
            self.set_label(_("Accepted name"))
            # create clickable label that will select the synonym
            # in the search results
            box = gtk.EventBox()
            label = gtk.Label()
            label.set_alignment(0, .5)
            label.set_markup(accepted.str(markup=True, authors=True))
            box.add(label)
            utils.make_label_clickable(label, on_label_clicked, accepted)
            syn_box.pack_start(box, expand=False, fill=False)
            self.show_all()
            self.set_sensitive(True)
            self.set_expanded(True)
        elif len(row.synonyms) == 0:
            self.set_sensitive(False)
            self.set_expanded(False)
        else:
            # remove all the children
            syn_box.foreach(syn_box.remove)
            for syn in row.synonyms:
                # create clickable label that will select the synonym
                # in the search results
                box = gtk.EventBox()
                label = gtk.Label()
                label.set_alignment(0, .5)
                label.set_markup(syn.str(markup=True, authors=True))
                box.add(label)
                utils.make_label_clickable(label, on_label_clicked, syn)
                syn_box.pack_start(box, expand=False, fill=False)
            self.show_all()
            self.set_sensitive(True)
            # TODO: get expanded state from prefs
            self.set_expanded(True)

Example 44

Project: bauble.classic
Source File: species.py
View license
    def update(self, row):
        '''
        update the expander

        :param row: the row to get the values from
        '''
        self.current_obj = row
        session = object_session(row)
        # link function
        on_label_clicked = lambda l, e, x: select_in_search_results(x)
        # Link to family
        self.widget_set_value('sp_fam_data', '<small>(%s)</small>' %
                              row.genus.family.family, markup=True)
        utils.make_label_clickable(
            self.widgets.sp_fam_data, on_label_clicked, row.genus.family)
        # link to genus
        self.widget_set_value('sp_gen_data', '<big><i>%s</i></big>' %
                              row.genus.genus, markup=True)
        utils.make_label_clickable(
            self.widgets.sp_gen_data, on_label_clicked, row.genus)
        # epithet (full binomial but missing genus)
        self.widget_set_value('sp_epithet_data', '<big>%s</big>' %
                              row.markup(authors=True, genus=False),
                              markup=True)

        awards = ''
        if row.awards:
            awards = utils.utf8(row.awards)
        self.widget_set_value('sp_awards_data', awards)

        logger.debug('setting cites data from row %s' % row)
        cites = ''
        if row.cites:
            cites = utils.utf8(row.cites)
        self.widget_set_value('sp_cites_data', cites)

        # zone = ''
        # if row.hardiness_zone:
        #     awards = utils.utf8(row.hardiness_zone)
        # self.widget_set_value('sp_hardiness_data', zone)

        habit = ''
        if row.habit:
            habit = utils.utf8(row.habit)
        self.widget_set_value('sp_habit_data', habit)

        dist = ''
        if row.distribution:
            dist = utils.utf8(row.distribution_str())
        self.widget_set_value('sp_dist_data', dist)

        dist = ''
        if row.label_distribution:
            dist = row.label_distribution
        self.widget_set_value('sp_labeldist_data', dist)

        # stop here if not GardenPluin
        if 'GardenPlugin' not in pluginmgr.plugins:
            return

        from bauble.plugins.garden.accession import Accession
        from bauble.plugins.garden.plant import Plant

        nacc = session.query(Accession).join('species').\
            filter_by(id=row.id).count()
        self.widget_set_value('sp_nacc_data', nacc)

        nplants = session.query(Plant).join('accession', 'species').\
            filter_by(id=row.id).count()
        if nplants == 0:
            self.widget_set_value('sp_nplants_data', nplants)
        else:
            nacc_in_plants = session.query(Plant.accession_id).\
                join('accession', 'species').\
                filter_by(id=row.id).distinct().count()
            self.widget_set_value('sp_nplants_data', '%s in %s accessions'
                                  % (nplants, nacc_in_plants))

Example 45

Project: bauble.classic
Source File: __init__.py
View license
def remove_callback(tags):
    """
    :param tags: a list of :class:`Tag` objects.
    """
    tag = tags[0]
    s = '%s: %s' % (tag.__class__.__name__, utils.xml_safe(tag))
    msg = _("Are you sure you want to remove %s?") % s
    if not utils.yes_no_dialog(msg):
        return
    session = object_session(tag)
    try:
        obj = session.query(Tag).get(tag.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe(e)
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)

    # reinitialize the tag menu
    _reset_tags_menu()
    return True

Example 46

Project: bauble.classic
Source File: __init__.py
View license
def untag_objects(name, objs):
    """
    Remove the tag name from objs.

    :param name: The name of the tag
    :type name: str
    :param objs: The list of objects to untag.
    :type objs: list
    """
    # TODO: should we loop through objects in a tag to delete
    # the TaggedObject or should we delete tags is they match
    # the tag in TaggedObj.selectBy(obj_class=classname, obj_id=obj.id)
    name = utils.utf8(name)
    if not objs:
        create_named_empty_tag(name)
        return
    session = object_session(objs[0])
    try:
        tag = session.query(Tag).filter_by(tag=name).one()
    except Exception, e:
        logger.info("%s - %s" % (type(e), e))
        logger.debug(traceback.format_exc())
        return
    same = lambda x, y: x.obj_class == _classname(y) and x.obj_id == y.id
    for obj in objs:
        for kid in tag._objects:
            if same(kid, obj):
                o = session.query(type(kid)).filter_by(id=kid.id).one()
                session.delete(o)
    session.commit()

Example 47

Project: bauble.classic
Source File: __init__.py
View license
def tag_objects(name, objs):
    """
    Tag a list of objects.

    :param name: The tag name, if it's a str object then it will be
      converted to unicode() using the default encoding. If a tag with
      this name doesn't exist it will be created
    :type name: str
    :param obj: A list of mapped objects to tag.
    :type obj: list
    """
    name = utils.utf8(name)
    if not objs:
        create_named_empty_tag(name)
        return
    session = object_session(objs[0])
    try:
        tag = session.query(Tag).filter_by(tag=name).one()
    except InvalidRequestError, e:
        logger.debug("%s - %s" % (type(e), e))
        tag = Tag(tag=name)
        session.add(tag)
    for obj in objs:
        cls = and_(TaggedObj.obj_class == _classname(obj),
                   TaggedObj.obj_id == obj.id,
                   TaggedObj.tag_id == tag.id)
        ntagged = session.query(TaggedObj).filter(cls).count()
        if ntagged == 0:
            tagged_obj = TaggedObj(obj_class=_classname(obj), obj_id=obj.id,
                                   tag=tag)
            session.add(tagged_obj)
    # if a new tag is created with the name parameter it is always saved
    # regardless of whether the objects are tagged
    session.commit()

Example 48

Project: bauble.classic
Source File: __init__.py
View license
def get_tag_ids(objs):
    """
    :param objs: a list or tuple of objects

    Return a list of tag id's for tags associated with obj, only returns those
    tag ids that are common between all the objs
    """
    # TODO: this function does intersection in the most
    # straightforward way and could probably do with some optimization
    #clause = lambda x: and_(TaggedObj.obj_class==_classname(x),
    #                        TaggedObj.obj_id==x.id)
    #ors = or_(*map(clause, objs))
    if not objs:
        return []
    session = object_session(objs[0])
    s = set()
    tag_id_query = session.query(Tag.id).join('_objects')
    for obj in objs:
        clause = and_(TaggedObj.obj_class == _classname(obj),
                      TaggedObj.obj_id == obj.id)
        tags = [r[0] for r in tag_id_query.filter(clause)]
        if len(s) == 0:
            s.update(tags)
        else:
            s.intersection_update(tags)
    return list(s)

Example 49

Project: iktomi
Source File: files.py
View license
    def __get__(self, inst, cls=None):
        if inst is None:
            return self
        if inst not in self._states:
            # XXX column name may differ from attribute name
            # empty string should be considered as None
            value = getattr(inst, self.attribute_name) or None
            if value is not None:
                session = object_session(inst)
                if session is None:
                    raise RuntimeError('Object is detached')
                if not hasattr(session, 'file_manager'):
                    raise RuntimeError(
                            "Session doesn't support file management")
                file_manager = session.find_file_manager(self)
                value = file_manager.get_persistent(value.decode('utf-8'),
                                                    self.persistent_cls)

                for file_attr, target_attr in self.cache_properties.items():
                    setattr(value, file_attr, getattr(inst, target_attr))

            self._states[inst] = value
        return self._states[inst]

Example 50

Project: iktomi
Source File: images.py
View license
    def _2persistent(self, target, transient):
        # XXX move this method to file_manager

        # XXX Do this check or not?
        image = Image.open(transient.path)
        assert image.format in Image.SAVE and image.format != 'bmp',\
                'Unsupported image format'

        if self.prop.image_sizes:
            session = object_session(target)
            persistent_name = getattr(target, self.prop.attribute_name)
            if isinstance(persistent_name, six.binary_type):
                persistent_name = persistent_name.decode('utf-8')
            pn, ext = os.path.splitext(persistent_name)

            image_crop = self.prop.resize(image, self.prop.image_sizes)

            if self.prop.force_rgb and image_crop.mode not in ['RGB', 'RGBA']:
                image_crop = image_crop.convert('RGB')
                if ext == '.gif':
                    image_crop.format = 'jpeg'
                    ext = '.jpeg'

            if self.prop.enhancements:
                for enhance, factor in self.prop.enhancements:
                    image_crop = enhance(image_crop).enhance(factor)

            if self.prop.filter:
                image_crop = image_crop.filter(self.prop.filter)

            if not ext:
                # set extension if it is not set
                ext = '.' + image.format.lower()

            if pn + ext != persistent_name:
                persistent_name = pn + ext
                # XXX hack?
                setattr(target, self.prop.attribute_name, persistent_name.encode('utf-8'))

            image_attr = getattr(target.__class__, self.prop.key)
            file_manager = persistent = session.find_file_manager(image_attr)
            persistent = file_manager.get_persistent(persistent_name,
                                                     self.prop.persistent_cls)

            transient = session.find_file_manager(image_attr).new_transient(ext)
            kw = dict(quality=self.prop.quality)
            if self.prop.optimize:
                kw = dict(kw, optimize=True)
            image_crop.save(transient.path, **kw)
            session.find_file_manager(image_attr).store(transient, persistent)
            return persistent
        else:
            # Attention! This method can accept PersistentFile.
            # In this case one shold NEVER been deleted or rewritten.
            assert isinstance(transient, TransientFile), repr(transient)
            return FileEventHandlers._2persistent(self, target, transient)