Here are the examples of the python api sqlalchemy.orm.object_session taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
85 Examples
3
Example 1
Project: sqlalchemy-continuum Source File: fetcher.py
def _next_prev_query(self, obj, next_or_prev='next'):
session = sa.orm.object_session(obj)
return (
session.query(obj.__class__)
.filter(
sa.and_(
getattr(
obj.__class__,
tx_column_name(obj)
)
==
self._transaction_id_subquery(
obj, next_or_prev=next_or_prev
),
*parent_criteria(obj)
)
)
)
3
Example 2
def _update_field(obj, field, value):
session = sa.orm.object_session(obj)
column = sa.inspect(obj.__class__).columns[field]
query = column.table.update().values(**{column.key: value})
session.execute(query)
session.flush()
3
Example 3
@property
def likes(self):
session = object_session(self)
return session.cache.get_or_create(
str("list:%s:thread:%s:likes" % (self.list_name, self.thread_id)),
lambda: self._getvotes().filter(Vote.value == 1).count()
)
3
Example 4
Project: Camelot Source File: batch_job.py
def add_strings_to_message( self, strings, color = None ):
"""Add strings to the message of this batch job.
:param strings: a list or generator of strings
:param color: the html color to be used for the strings (`'red'`,
`'green'`, ...), None if the color needs no change.
"""
if color:
strings = [u'<font color="%s">'%color] + strings + [u'</font>']
session = orm.object_session( self )
# message might be changed in the orm
session.commit()
batch_table = self.__table__
update = batch_table.update().where( batch_table.c.id == self.id )
update = update.values( message = sql.func.coalesce( batch_table.c.message, '' ) + sql.bindparam('line') )
for line in strings:
session.execute( update, params = {'line':line + '<br/>'} )
session.commit()
3
Example 5
def model_run( self, model_context ):
from sqlalchemy.orm import object_session
from camelot.view import action_steps
obj_getter = yield action_steps.SelectObject( model_context.admin )
if obj_getter != None:
obj_to_add = obj_getter()
for obj in model_context.get_collection():
if obj_to_add == obj:
raise StopIteration()
model_context._model.append_object( obj_to_add, flush = False )
yield action_steps.FlushSession( object_session( obj_to_add ) )
3
Example 6
@property
def participants_count(self):
session = object_session(self)
return session.cache.get_or_create(
str("list:%s:thread:%s:participants_count"
% (self.list_name, self.thread_id)),
lambda: self._get_participants().count())
3
Example 7
Project: sqlalchemy-continuum Source File: property_mod_tracker.py
def after_create_version_object(self, uow, parent_obj, version_obj):
session = sa.orm.object_session(parent_obj)
is_deleted = parent_obj in session.deleted
for prop in versioned_column_properties(parent_obj):
if has_changes(parent_obj, prop.key) or is_deleted:
setattr(
version_obj,
prop.key + self.column_suffix,
True
)
3
Example 8
@property
def recent_participants_count(self):
begin_date, end_date = self.get_recent_dates()
session = object_session(self)
return session.cache.get_or_create(
str("list:%s:recent_participants_count" % self.name),
lambda: get_participants_count_between(session, self.name,
begin_date, end_date),
86400)
3
Example 9
Project: sqlalchemy-utils Source File: observer.py
def get_callback_args(self, root_obj, callback):
session = sa.orm.object_session(root_obj)
objects = [getdotattr(
root_obj,
path,
lambda obj: obj not in session.deleted
) for path in callback.fullpath]
paths = [str(path) for path in callback.fullpath]
for path in paths:
if '.' in path or has_changes(root_obj, path):
return (
root_obj,
callback.func,
objects
)
3
Example 10
def get_month_activity(self, year, month):
session = object_session(self)
begin_date = datetime.datetime(year, month, 1)
end_date = begin_date + datetime.timedelta(days=32)
end_date = end_date.replace(day=1)
participants_count = session.cache.get_or_create(
str("list:%s:participants_count:%s:%s" % (self.name, year, month)),
lambda: get_participants_count_between(session, self.name,
begin_date, end_date),
)
threads_count = session.cache.get_or_create(
str("list:%s:threads_count:%s:%s" % (self.name, year, month)),
lambda: get_threads_between(session, self.name,
begin_date, end_date).count(),
)
Activity = namedtuple('Activity',
['year', 'month', 'participants_count', 'threads_count'])
return Activity(year, month, participants_count, threads_count)
3
Example 11
Project: Camelot Source File: authentication.py
def get_current_authentication( _obj = None ):
"""Get the currently logged in :class:'AuthenticationMechanism'"""
global _current_authentication_
if not hasattr( _current_authentication_, 'mechanism' ) \
or not _current_authentication_.mechanism \
or not orm.object_session( _current_authentication_.mechanism ):
import getpass
_current_authentication_.mechanism = AuthenticationMechanism.get_or_create( unicode( getpass.getuser(), encoding='utf-8', errors='ignore' ) )
return _current_authentication_.mechanism
3
Example 12
@model_function
def refresh(self, entity_instance):
"""Undo the pending changes to the backend and restore the original
state"""
session = orm.object_session( entity_instance )
if session:
objects_to_refresh = set([entity_instance])
self._expand_compounding_objects( objects_to_refresh )
for obj in objects_to_refresh:
if obj in session:
session.refresh( obj )
3
Example 13
Project: kittystore Source File: model.py
@property
def starting_email(self):
"""Return (and cache) the email starting this thread"""
session = object_session(self)
message_id = session.cache.get_or_create(
str("list:%s:thread:%s:starting_email_id"
% (self.list_name, self.thread_id)),
lambda: session.query(Email.message_id).with_parent(self).order_by(
Email.in_reply_to != None, Email.date).limit(1).scalar(),
should_cache_fn=lambda val: val is not None
)
if message_id is not None:
return session.query(Email).get((self.list_name, message_id))
3
Example 14
def test_delete_selection( self ):
session = orm.object_session( self.context.obj )
self.assertTrue( self.context.obj in session )
delete_selection_action = list_action.DeleteSelection()
delete_selection_action.gui_run( self.gui_context )
list( delete_selection_action.model_run( self.context ) )
self.assertFalse( self.context.obj in session )
3
Example 15
def printstatus(obj):
"""
print an object's status regarding the sqla's session
"""
from sqlalchemy.orm import object_session
from sqlalchemy.orm.util import has_identity
if object_session(obj) is None and not has_identity(obj):
print "Sqlalchemy status : transient"
elif object_session(obj) is not None and not has_identity(obj):
print "Sqlalchemy status : pending"
elif object_session(obj) is None and has_identity(obj):
print "Sqlalchemy status : detached"
elif object_session(obj) is not None and has_identity(obj):
print "Sqlalchemy status : persistent"
else:
print "Unknown Status"
3
Example 16
Project: sqlalchemy-continuum Source File: fetcher.py
def previous_query(self, obj):
"""
Returns the query that fetches the previous version relative to this
version in the version history.
"""
session = sa.orm.object_session(obj)
return (
session.query(obj.__class__)
.filter(
sa.and_(
getattr(obj.__class__, end_tx_column_name(obj))
==
getattr(obj, tx_column_name(obj)),
*parent_criteria(obj)
)
)
)
3
Example 17
@property
def emails_count(self):
session = object_session(self)
return session.cache.get_or_create(
str("list:%s:thread:%s:emails_count"
% (self.list_name, self.thread_id)),
lambda: session.query(Email).with_parent(self).count())
3
Example 18
Project: sqlalchemy-continuum Source File: utils.py
def is_modified_or_deleted(obj):
"""
Return whether or not some of the versioned properties of given SQLAlchemy
declarative object have been modified or if the object has been deleted.
:param obj: SQLAlchemy declarative model object
"""
session = sa.orm.object_session(obj)
return is_versioned(obj) and (
is_modified(obj) or
obj in chain(session.deleted, session.new)
)
3
Example 19
Project: bauble.classic Source File: __init__.py
def delete_or_expunge(obj):
"""
If the object is in object_session(obj).new then expunge it from the
session. If not then session.delete it.
"""
from sqlalchemy.orm import object_session
session = object_session(obj)
if session is None:
return
if obj not in session.new:
logger.debug('delete obj: %s -- %s' % (obj, repr(obj)))
session.delete(obj)
else:
logger.debug('expunge obj: %s -- %s' % (obj, repr(obj)))
session.expunge(obj)
del obj
3
Example 20
Project: sqlalchemy-utils Source File: asserts.py
def _expect_failing_update(obj, field, value, expected_exc):
try:
_update_field(obj, field, value)
except expected_exc:
pass
else:
raise AssertionError('Expected update to raise %s' % expected_exc)
finally:
session = sa.orm.object_session(obj)
session.rollback()
3
Example 21
Project: kittystore Source File: model.py
@sa_event.listens_for(Thread, 'before_insert')
def Thread_before_insert(mapper, connection, target):
"""Auto-set the active date from the last email in thread"""
if target.date_active is not None:
return
session = object_session(target)
last_email_date = session.query(Email.date).order_by(
desc(Email.date)).limit(1).scalar()
if last_email_date:
target.date_active = last_email_date
else:
target.date_active = datetime.datetime.now()
3
Example 22
Project: indico Source File: users.py
@listens_for(User._primary_email, 'set')
@listens_for(User._secondary_emails, 'append')
@listens_for(User._secondary_emails, 'remove')
def _user_email_changed(target, value, *unused):
# all_emails is out of sync when changing the emails
sess = object_session(target)
if sess is not None:
sess.expire(target, ['_all_emails'])
3
Example 23
Project: iktomi Source File: replication.py
def reflect(source, model, cache=None):
'''Finds an object of class `model` with the same identifier as the
`source` object'''
if source is None:
return None
if cache and source in cache:
return cache[source]
db = object_session(source)
ident = identity_key(instance=source)[1]
assert ident is not None
return db.query(model).get(ident)
3
Example 24
@model_function
def expunge(self, entity_instance):
"""Expunge the entity from the session"""
session = orm.object_session( entity_instance )
if session:
objects_to_expunge = set([entity_instance])
self._expand_compounding_objects( objects_to_expunge )
for obj in objects_to_expunge:
if obj in session:
session.expunge( obj )
3
Example 25
def get_votes_in_list(self, list_name):
session = object_session(self)
def getvotes():
req = session.query(Vote).filter(Vote.list_name == list_name)
likes = req.filter(Vote.value == 1).count()
dislikes = req.filter(Vote.value == -1).count()
return likes, dislikes # TODO: optimize with a Union statement?
cache_key = str("user:%s:list:%s:votes" % (self.id.int, list_name))
return session.cache.get_or_create(cache_key, getvotes)
3
Example 26
def transaction( original_function ):
"""Decorator to make methods transactional with regard to the session
of the object on which they are called"""
@functools.wraps( original_function )
def decorated_function( self, *args, **kwargs ):
session = orm.object_session( self )
with session.begin():
return original_function( self, *args, **kwargs )
return decorated_function
3
Example 27
def validate_object( self, obj ):
""":return: list of messages explaining invalid data
empty list if object is valid
"""
session = orm.object_session( obj )
if session == None:
return []
if obj in session.deleted:
return []
return super( EntityValidator, self ).validate_object( obj )
3
Example 28
@property
def dislikes(self):
session = object_session(self)
return session.cache.get_or_create(
str("list:%s:email:%s:dislikes" % (self.list_name, self.message_id)),
lambda: self._get_votes_query().filter(Vote.value == -1).count()
)
3
Example 29
Project: Camelot Source File: authentication.py
def update_last_login():
"""Update the last login of the current person to now"""
authentication = get_current_authentication()
authentication.last_login = datetime.datetime.now()
session = orm.object_session( authentication )
if session:
session.flush()
3
Example 30
def __session(self):
sess = object_session(self.instance)
if sess is not None and self.autoflush and sess.autoflush \
and self.instance in sess:
sess.flush()
if not has_identity(self.instance):
return None
else:
return sess
3
Example 31
Project: Camelot Source File: party.py
def _set_address_field( self, name, value ):
if not self.addresses:
address = PartyAddress()
self.addresses.append( address )
address = self.addresses[0]
setattr( address, name, value )
if address.street1==None and address.street2==None and address.city==None:
session = orm.object_session( address )
if address in session.new:
session.expunge( address )
self.addresses.remove( address )
else:
session.delete( address )
3
Example 32
Project: kittystore Source File: model.py
def _get_participants(self):
"""Email senders in this thread"""
session = object_session(self)
return session.query(Sender).join(Email).filter(and_(
Email.list_name == self.list_name,
Email.thread_id == self.thread_id,
)).distinct()
3
Example 33
def index(self, obj):
"""
Return the index of this version in the version history.
"""
session = sa.orm.object_session(obj)
return session.execute(self._index_query(obj)).fetchone()[0]
3
Example 34
Project: bauble.classic Source File: __init__.py
def __init__(self, species, for_labels=False):
super(SpeciesABCDAdapter, self).__init__(species)
# hold on to the accession so it doesn't get cleaned up and closed
self.session = object_session(species)
self.for_labels = for_labels
self.species = species
self._date_format = prefs.prefs[prefs.date_format_pref]
3
Example 35
Project: sqlalchemy-continuum Source File: fetcher.py
def next_query(self, obj):
"""
Returns the query that fetches the next version relative to this
version in the version history.
"""
session = sa.orm.object_session(obj)
return (
session.query(obj.__class__)
.filter(
sa.and_(
getattr(obj.__class__, tx_column_name(obj))
==
getattr(obj, end_tx_column_name(obj)),
*parent_criteria(obj)
)
)
)
3
Example 36
def _set_category(self, name):
if not name:
self.category_id = None
return
session = object_session(self)
try:
category = session.query(Category).filter_by(name=name).one()
except NoResultFound:
category = Category(name=name)
session.add(category)
self.category_id = category.id
3
Example 37
Project: sqlalchemy-continuum Source File: manager.py
def tracked_operation(func):
@wraps(func)
def wrapper(self, mapper, connection, target):
if not is_versioned(target):
return
session = object_session(target)
conn = session.connection()
try:
uow = self.units_of_work[conn]
except KeyError:
uow = self.units_of_work[conn.engine]
return func(self, uow, target)
return wrapper
3
Example 38
Project: formalchemy Source File: tables.py
def bind(self, instances, session=None, data=None, request=None):
"""bind to instances"""
_validate_iterable(instances)
if not session:
i = iter(instances)
try:
instance = next(i)
except StopIteration:
pass
else:
from sqlalchemy.orm import object_session
session = object_session(instance)
mr = FieldSet.bind(self, self.model, session, data, request)
mr.rows = instances
mr._request = request
return mr
3
Example 39
def query(self, obj):
session = sa.orm.object_session(obj)
return (
session.query(self.remote_cls)
.filter(
self.criteria(obj)
)
)
3
Example 40
@property
def subject(self):
session = object_session(self)
return session.cache.get_or_create(
str("list:%s:thread:%s:subject"
% (self.list_name, self.thread_id)),
lambda: self.starting_email.subject)
3
Example 41
def fetch(self, locale):
session = sa.orm.object_session(self.obj)
# If the object has no identity and its not in session or if the object
# has _translations relationship loaded get the locale object from the
# relationship.
if '_translations' not in sa.inspect(self.obj).unloaded or (
not session or not has_identity(self.obj)
):
return self.obj._translations.get(locale)
return session.query(self.obj.__translatable__['class']).get(
sa.inspect(self.obj).identity + (locale, )
)
3
Example 42
@property
def book(self):
"""Return the gnc book holding the object
"""
s = object_session(self)
return s and s.book
3
Example 43
Project: sqlalchemy-utils Source File: asserts.py
def _expect_successful_update(obj, field, value, reraise_exc):
try:
_update_field(obj, field, value)
except (reraise_exc) as e:
session = sa.orm.object_session(obj)
session.rollback()
assert False, str(e)
3
Example 44
@property
def dislikes(self):
session = object_session(self)
return session.cache.get_or_create(
str("list:%s:thread:%s:dislikes"
% (self.list_name, self.thread_id)),
lambda: self._getvotes().filter(Vote.value == -1).count()
)
3
Example 45
@property
def recent_threads_count(self):
begin_date, end_date = self.get_recent_dates()
session = object_session(self)
return session.cache.get_or_create(
str("list:%s:recent_threads_count" % self.name),
lambda: get_threads_between(session, self.name,
begin_date, end_date).count(),
86400)
3
Example 46
@event.listens_for(SlotFrame.slots, 'remove')
def remove_slot(target, value, initiator):
s = object_session(value)
if value in s.new:
s.expunge(value)
else:
s.delete(value)
3
Example 47
@classmethod
def __declare_last__(cls):
# do not do it on the DeclarativeBaseGuid as it is an abstract class
if cls == DeclarativeBaseGuid:
return
# assign id of slot when associating to object
@event.listens_for(cls.slots, "remove")
def my_append_listener_slots(target, value, initiator):
s = object_session(value)
if s:
if value in s.new:
s.expunge(value)
else:
s.delete(value)
3
Example 48
def replicate(source, model, cache=None):
'''Replicates the `source` object to `model` class and returns its
reflection.'''
target = replicate_no_merge(source, model, cache=cache)
if target is not None:
db = object_session(source)
target = db.merge(target)
return target
3
Example 49
@property
def likes(self):
session = object_session(self)
return session.cache.get_or_create(
str("list:%s:email:%s:likes" % (self.list_name, self.message_id)),
lambda: self._get_votes_query().filter(Vote.value == 1).count()
)
3
Example 50
def __init__( self, *args, **kwargs ):
_declarative_constructor( self, *args, **kwargs )
# due to cascading rules and a constructor argument, the object might
# allready be in a session
if orm.object_session( self ) == None:
Session().add( self )