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.
51 Examples
3
Example 1
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)
3
Example 2
@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
3
Example 3
@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
3
Example 4
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)
3
Example 5
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)
3
Example 6
Project: indico Source File: surveys.py
@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'])
3
Example 7
Project: ghini.desktop Source File: location.py
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)
3
Example 8
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
3
Example 9
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
3
Example 10
@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
3
Example 11
Project: bauble.classic Source File: __init__.py
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
3
Example 12
Project: bauble.classic Source File: location.py
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)
3
Example 13
Project: sqlalchemy-i18n Source File: manager.py
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)
3
Example 14
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)
3
Example 15
@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)
3
Example 16
Project: pokedex Source File: multilang.py
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
3
Example 17
@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)
3
Example 18
Project: bauble.classic Source File: __init__.py
@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()]
3
Example 19
@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)
3
Example 20
@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)
0
Example 21
Project: pokedex Source File: markdown.py
def _markdownify_effect_text(move, effect_text, language=None):
session = object_session(move)
if effect_text is None:
return effect_text
effect_text = effect_text.replace(
u'$effect_chance',
str(move.effect_chance),
)
# "The target" vs "each target"; for Conquest, but hopefully main series
# moves too eventually
if hasattr(move, 'range'):
effect_text = effect_text.replace(
u'$target',
_target_labels[move.range.targets > 1]
).replace(
u'$Target',
_target_labels[move.range.targets > 1].capitalize()
)
return MarkdownString(effect_text, session, language)
0
Example 22
Project: bauble.classic Source File: species.py
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))
0
Example 23
@is_active.setter
def is_active(self, value):
"""
Set user as active/inactive.
:param bood value:
True - removes deactivated_at, deleted_at, activate_key and set activated_at to datetime now
False - set deactivated_at to now and activated_at to None
"""
# Allow to modify this only if object is in the persistent state to prevent "default values" errors/bugs.
# http://stackoverflow.com/questions/3885601/sqlalchemy-get-object-instance-state
if object_session(self) is not None and has_identity(self):
if value:
self.deactivated_at = None
self.deleted_at = None
self.activate_key = None
self.activated_at = datetime.now()
else:
self.deactivated_at = datetime.now()
self.activated_at = None
else:
raise AttributeError('User has to be in the persistent state - stored in the DB')
0
Example 24
Project: ghini.desktop Source File: genus.py
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.epithet.like('%s%%' % text)).\
order_by(Family.epithet)
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', 'epithet',
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
0
Example 25
Project: bauble.classic Source File: family.py
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))
0
Example 26
Project: ghini.desktop Source File: genus.py
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.str(use_hybrid_marker=True),
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))
0
Example 27
Project: ghini.desktop Source File: species.py
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.epithet, markup=True)
utils.make_label_clickable(
self.widgets.sp_fam_data, on_label_clicked, row.genus.family)
# link to genus
if row.hybrid_marker != u'H':
self.widget_set_value('sp_gen_data', '<big><i>%s</i></big> ' %
row.genus.str(use_hybrid_marker=True),
markup=True)
utils.make_label_clickable(
self.widgets.sp_gen_data, on_label_clicked, row.genus)
else:
self.widget_set_value('sp_gen_data', '')
# 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))
0
Example 28
Project: bauble.classic Source File: species.py
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)
0
Example 29
Project: bauble.classic Source File: family.py
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
0
Example 30
Project: snorkel Source File: context.py
def child_context_stats(self, parent_context):
"""
Given a parent context class, gets all the child context classes, and returns histograms of the number
of children per parent.
"""
session = object_session(self)
parent_name = parent_context.__table__.name
# Get all the child context relationships
rels = [r for r in inspect(parent_context).relationships if r.back_populates == parent_name]
# Print the histograms for each child context, and recurse!
for rel in rels:
c = rel.mapper.class_
fk = list(rel._calculated_foreign_keys)[0]
# Query for average number of child contexts per parent context
label = 'Number of %ss per %s' % (c.__table__.name, parent_name)
query = session.query(fk, func.count(c.id).label(label)).group_by(fk)
# Render as panadas dataframe histogram
df = pd.read_sql(query.statement, query.session.bind)
df.hist(label)
# Recurse to grandhildren
self.child_context_stats(c)
0
Example 31
Project: ghini.desktop Source File: family.py
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.synonyms_presenter = SynonymsPresenter(self)
self.refresh_view() # put model values in view
# connect signals
self.assign_simple_handler('fam_family_entry', 'epithet',
editor.UnicodeOrNoneValidator())
self.assign_simple_handler('fam_aggregate_combo', 'aggregate',
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
0
Example 32
Project: bauble.classic Source File: genus.py
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
0
Example 33
@property
def session(self):
return object_session(self)
0
Example 34
Project: bauble.classic Source File: propagation.py
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)
0
Example 35
Project: bauble.classic Source File: family.py
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
0
Example 36
Project: bauble.classic Source File: __init__.py
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()
0
Example 37
Project: webcheck Source File: db.py
@property
def count_parents(self):
session = object_session(self)
return session.query(children.c.parent_id).filter(children.c.child_id == self.id).union(
session.query(embedded.c.parent_id).filter(embedded.c.child_id == self.id)).count()
0
Example 38
@property
def objects(self):
"""return all tagged objects
reuse last result if nothing was changed in the database since
list was retrieved.
"""
if self.__my_own_timestamp is not None:
# should I update my list?
session = object_session(self)
last_history = session.query(db.History)\
.order_by(db.History.timestamp.desc())\
.limit(1).one()
if last_history.timestamp > self.__my_own_timestamp:
self.__last_objects = None
if self.__last_objects is None:
# here I update my list
from datetime import datetime
self.__my_own_timestamp = datetime.now()
self.__last_objects = self.get_tagged_objects()
# here I return my list
return self.__last_objects
0
Example 39
Project: bauble.classic Source File: __init__.py
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
0
Example 40
Project: sync-engine Source File: gmail.py
def _get_token(self, account, scope, force_refresh=False):
if not force_refresh:
try:
gtoken = self._tokens[account.id][scope]
if datetime.utcnow() < gtoken.expiration:
return gtoken
except KeyError:
pass
# If we find invalid GmailAuthCredentials while trying to
# get a new token, we mark them as invalid. We want to make
# sure we commit those changes to the database before we
# actually throw an error.
try:
gtoken = account.new_token(scope)
except (ConnectionError, OAuthError):
if object_session(account):
object_session(account).commit()
else:
with session_scope(account.id) as db_session:
db_session.merge(account)
db_session.commit()
raise
self.cache_token(account, gtoken)
return gtoken
0
Example 41
Project: bauble.classic Source File: __init__.py
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)
0
Example 42
Project: bauble.classic Source File: genus.py
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
0
Example 43
Project: bauble.classic Source File: genus.py
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))
0
Example 44
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]
0
Example 45
Project: bauble.classic Source File: __init__.py
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()
0
Example 46
Project: bauble.classic Source File: location.py
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)
0
Example 47
Project: bauble.classic Source File: propagation.py
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)
0
Example 48
Project: iktomi Source File: images.py
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)
0
Example 49
Project: bauble.classic Source File: species.py
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
0
Example 50
Project: iktomi Source File: images.py
def _fill_img(self, mapper, connection, target):
if self.prop.fill_from:
# XXX Looks hacky
value = getattr(target, self.prop.key)
if value is None:
base = getattr(target, self.prop.fill_from)
if base is None:
return
if not os.path.isfile(base.path):
logger.warn('Original file is absent %s %s %s',
identity_key(instance=target),
self.prop.fill_from,
base.path)
return
ext = os.path.splitext(base.name)[1]
session = object_session(target)
image_attr = getattr(target.__class__, self.prop.key)
name = session.find_file_manager(image_attr).new_file_name(
self.prop.name_template, target, ext, '')
setattr(target, self.prop.attribute_name, name)
persistent = self._2persistent(target, base)
setattr(target, self.prop.key, persistent)