本文整理汇总了Python中sqlalchemy.orm.util.has_identity函数的典型用法代码示例。如果您正苦于以下问题:Python has_identity函数的具体用法?Python has_identity怎么用?Python has_identity使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了has_identity函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:FelixLoether,项目名称:wtforms-alchemy,代码行数:9,代码来源:__init__.py
示例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
开发者ID:prinzdezibel,项目名称:p2.datashackle.core,代码行数:10,代码来源:model.py
示例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()
开发者ID:Byron,项目名称:bit,代码行数:50,代码来源:test_sql.py
示例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)
开发者ID:NSkelsey,项目名称:research,代码行数:15,代码来源:usefulfunctions.py
示例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)
开发者ID:FelixLoether,项目名称:wtforms-alchemy,代码行数:16,代码来源:__init__.py
示例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()
开发者ID:joneshf,项目名称:alchemist,代码行数:30,代码来源:models.py
示例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()
开发者ID:sopython,项目名称:rabbit,代码行数:28,代码来源:dbmodel.py
示例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
开发者ID:jessedhillon,项目名称:batteries,代码行数:31,代码来源:serializable.py
示例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"
开发者ID:mike-perdide,项目名称:autonomie,代码行数:16,代码来源:base.py
示例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]
开发者ID:devhub,项目名称:baph,代码行数:29,代码来源:forms.py
示例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)
开发者ID:gsakkis,项目名称:fixture,代码行数:8,代码来源:sqlalchemy_loadable.py
示例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)
开发者ID:devhub,项目名称:baph,代码行数:8,代码来源:mixins.py
示例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
开发者ID:dreamwave,项目名称:rad,代码行数:8,代码来源:dynamic.py
示例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)
开发者ID:dieselmachine,项目名称:baph,代码行数:9,代码来源:mixins.py
示例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
开发者ID:dieselmachine,项目名称:baph,代码行数:9,代码来源:mixins.py
示例16: make_asset_key
def make_asset_key(self, key, asset_type=None):
"""
Generates an asset key, which will be invalidated when the
parent object is invalidated
"""
self.validate_cache_mode('asset')
if not has_identity(self):
raise Exception('This instance has no identity')
return self.build_cache_key('asset', key, asset_type,
**self.cache_data)
开发者ID:devhub,项目名称:baph,代码行数:10,代码来源:mixins.py
示例17: fetch
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, )
)
开发者ID:lelit,项目名称:sqlalchemy-i18n,代码行数:13,代码来源:translatable.py
示例18: __init__
def __init__(self, *args, **kwargs):
instance = kwargs.pop("instance", None)
nested = kwargs.pop("nested", False)
super(BaseSQLAModelForm, self).__init__(*args, **kwargs)
self.instance = instance
if instance and has_identity(instance):
excludes = self._meta.exclude_on_update[:]
else:
excludes = self._meta.exclude_on_create[:]
if nested:
excludes.extend(self._meta.exclude_on_nested)
for k in excludes:
if k in self.fields:
del self.fields[k]
开发者ID:dieselmachine,项目名称:baph,代码行数:14,代码来源:forms.py
示例19: save
def save(self, commit=False):
"""
Saves this ``form``'s cleaned_data into model instance
``self.instance``.
If commit=True, then the changes to ``instance`` will be saved to the
database. Returns ``instance``.
"""
if not has_identity(self.instance):
fail_message = 'created'
else:
fail_message = 'changed'
return save_instance(self, self.instance, self._meta.fields,
fail_message, commit, self._meta.exclude)
开发者ID:devhub,项目名称:baph,代码行数:14,代码来源:forms.py
示例20: is_transient
def is_transient(self):
"""True if the allocation does not exist in the database, and is not
about to be written to the database. If an allocation is transient it
means that the given instance only exists in memory.
See:
http://www.sqlalchemy.org/docs/orm/session.html
#quickie-intro-to-object-states
http://stackoverflow.com/questions/3885601/
sqlalchemy-get-object-instance-state
"""
return object_session(self) is None and not has_identity(self)
开发者ID:4teamwork,项目名称:seantis.reservation,代码行数:14,代码来源:allocation.py
注:本文中的sqlalchemy.orm.util.has_identity函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论