本文整理汇总了Python中sqlalchemy.orm.util.has_identity函数的典型用法代码示例。如果您正苦于以下问题:Python has_identity函数的具体用法?Python has_identity怎么用?Python has_identity使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了has_identity函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: delete_existing
def delete_existing(self, obj, name):
if has_identity(obj):
sess = session(obj)
items = getattr(obj, name, set([]))
while items:
item = items.pop()
# only delete persistent objects
if has_identity(item):
sess.delete(item)
示例2: get_object_state
def get_object_state(self):
if object_session(self) is None and not has_identity(self):
return 'transient'
elif object_session(self) is not None and not has_identity(self):
return 'pending'
elif object_session(self) is None and has_identity(self):
return 'detached'
elif object_session(self) is not None and has_identity(self):
return 'persistent'
raise Exception
示例3: test_sql_session
def test_sql_session(self, rw_dir):
"""Test basic SQL handling"""
session = PackageSession.new(url=self.temporary_sqlite_url(rw_dir))
assert len(list(session.query(SQLPackage))) == 0
now = datetime.now()
# Setup a package
pkg = SQLPackage(host='foo', root_path='path/foo', package_path='package_dir', managed_at=now, stable_since=now)
assert len(pkg.transactions) == 0
session.add(pkg)
session.commit()
assert has_identity(pkg)
assert session.to_sql_package(pkg) is pkg
# Create a new package, for the fun of it
dpkg = DummyPackage('hello/world', 'package')
self.failUnlessRaises(ValueError, session.to_sql_package, dpkg)
other_pkg = session.to_sql_package(dpkg, stable_since=10.0)
assert other_pkg != pkg
assert object_session(other_pkg) is session and not has_identity(other_pkg)
# unmanage the package and verify it's not returned
pkg.unmanage()
self.failUnlessRaises(ValueError, session.to_sql_package, pkg)
assert session.to_sql_package(pkg, managed_only=False) is pkg
# Setup a simple transaction
trans = SQLPackageTransaction(host='foo', type_name='testing', in_package=pkg,
in_package_stable_since = pkg.stable_since, spooled_at=now)
assert len(pkg.transactions) == 1
assert trans.in_package is pkg
assert trans.out_package is None
assert len(trans.files) == 0
session.add(trans)
session.commit()
# Add a transaction file
file = SQLTransactionFile(transaction = trans, path='foo/bar', size=14, uid=2, gid=1, mode=0)
assert len(trans.files) == 1 and trans.files[0] is file
assert file.transaction is trans
session.add(file)
session.commit()
# it will work indirectly as well
trans.files.append(SQLTransactionFile(path='foo/bar2', size=14, uid=2, gid=1, mode=0))
session.commit()
示例4: print_state
def print_state(obj):
from sqlalchemy.orm import object_session
from sqlalchemy.orm.util import has_identity
obj = obj
if object_session(obj) is None and not has_identity(obj):
print "transient:"
if object_session(obj) is not None and not has_identity(obj):
print "pending: "
if object_session(obj) is None and has_identity(obj):
print "# detached: "
if object_session(obj) is not None and has_identity(obj):
print "# persistent: "
print type(obj)
示例5: populate_obj
def populate_obj(self, obj, name):
if has_identity(obj):
sess = session(obj)
item = getattr(obj, name, None)
if item:
# only delete persistent objects
if has_identity(item):
sess.delete(item)
elif item in sess:
sess.expunge(item)
setattr(obj, name, None)
if self.data:
setattr(obj, name, self.form.Meta.model())
FormField.populate_obj(self, obj, name)
示例6: save
def save(self, session=None, commit=True):
"""
Save the changes to the model. If the model has not been persisted
then it adds the model to the declared session. Then it flushes the
object session and optionally commits it.
@param[in] session
A specific session to use instead of the thread-local, scoped
session.
"""
if has_identity(self):
# Object has already been persisted to the database; grab its
# session.
session = object_session(self)
else:
# Ensure we have a database session.
if session is None:
session = __import__('alchemist.db').db.session
# Object has not been persisted to the database.
session.add(self)
if commit:
# Commit the session as requested.
session.commit()
else:
# Just flush the session; do not commit.
session.flush()
示例7: update_from_SE
def update_from_SE(self, force=False, cache=timedelta(86400)):
if (
has_identity(self) and self.user_id and not force
and (datetime.utcnow() - self.updated) < cache
):
return self
user = requests.get(
'http://api.stackexchange.com/2.2/users/{}'.format(self.user_id),
{'site': 'stackoverflow'}
).json()['items'][0]
self.display_name = user['display_name']
self.reputation = user['reputation']
self.profile_image = user['profile_image']
self.user_type = user['user_type']
gold_badges = requests.get(
'http://api.stackexchange.com/2.2/users/{}/badges'.format(self.user_id),
{'site': 'stackoverflow', 'max': 'gold', 'sort': 'rank'}
).json()
self.gold_tag_badges = ' '.join(
badge['name'] for badge in gold_badges['items']
if badge['badge_type'] == 'tag_based'
)
self.updated = datetime.utcnow()
示例8: serialize
def serialize(self, fields=None, include=None, exclude=None):
obj = {}
if fields is None:
fields = set(self.__class__.serializable)
if include is not None:
fields |= set(include)
if exclude is not None:
fields ^= set(exclude)
for prop in fields:
serializer_name = "serialize_" + prop
if hasattr(self, serializer_name):
obj[prop] = getattr(self, serializer_name)()
else:
is_transient = object_session(self) is None and not has_identity(self)
if is_transient:
# transiet instances are not tied to a session,
# so we can't call getattr() because that can cause an attribute refresh,
# which is a hard SQLAlchemy error
v = self.__dict__.get(prop)
else:
v = getattr(self, prop)
serializers = self.__serializable_args__["serializers"]
opts = self.__serializable_args__["opts"]
obj[prop] = serialize(v, serializers, opts)
return obj
示例9: printstatus
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"
示例10: __init__
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, instance=None, nested=False, **kwargs):
opts = self._meta
exclude = list(opts.exclude)
if opts.model is None:
raise ValueError('ModelForm has no model class specified.')
self.nested = nested
if self.nested:
exclude.extend(opts.exclude_on_nested)
if instance is None:
exclude.extend(opts.exclude_on_create)
self.instance = opts.model()
object_data = {}
else:
self.instance = instance
object_data = model_to_dict(instance, opts.fields, exclude)
if has_identity(instance):
exclude.extend(opts.exclude_on_update)
else:
exclude.extend(opts.exclude_on_create)
if initial is not None:
object_data.update(initial)
object_data.update(data)
super(BaseSQLAModelForm, self).__init__(object_data, files, auto_id, prefix)
for k in exclude:
if k in self.fields:
del self.fields[k]
示例11: clear
def clear(self, obj):
"""Delete this object from the session"""
from sqlalchemy.orm.util import has_identity
if obj not in self.session:
# detached object; merge it with the one stored in session
obj = self.session.merge(obj)
if has_identity(obj):
self.session.delete(obj)
示例12: cache_key
def cache_key(self):
"""
Instance property which returns the cache key for a single object
"""
self.validate_cache_mode('detail')
if not has_identity(self):
raise Exception('This instance has no identity')
return self.build_cache_key('detail', **self.cache_data)
示例13: __session
def __session(self):
sess = object_session(self.instance)
if sess is not None and self.autoflush and sess.autoflush and self.instance in sess:
sess.flush()
if not has_identity(self.instance):
return None
else:
return sess
示例14: cache_detail_key
def cache_detail_key(self, data=None):
if not hasattr(self._meta, 'cache_detail_keys'):
raise Exception('Class meta has no cache_detail_keys')
if not has_identity(self):
raise Exception('Cannot generate detail cache key for instance ' \
'with no identity')
data = data or instance_dict(self)
raw_key, attrs = self._meta.cache_detail_keys[0]
return self.format_key(raw_key % data)
示例15: cache_list_version_key
def cache_list_version_key(self, data=None):
if not self._meta.cache_list_keys:
raise Exception('Class._meta has no cache_list_keys')
if not has_identity(self):
raise Exception('Cannot generate list cache key for instance ' \
'with no identity')
data = data or instance_dict(self)
raw_key, attrs = self._meta.cache_list_keys[0]
return raw_key % data