本文整理汇总了Python中django.db.transaction.savepoint方法的典型用法代码示例。如果您正苦于以下问题:Python transaction.savepoint方法的具体用法?Python transaction.savepoint怎么用?Python transaction.savepoint使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.transaction
的用法示例。
在下文中一共展示了transaction.savepoint方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_emptyfield
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def test_emptyfield(self):
m = self._get_mailinglist()
p = self._get_participant()
values = {
'author': p,
'timestamp': datetime.datetime.utcnow(),
'subject': '',
'message_id': 'abc'
}
for key in values:
kwargs = values.copy()
kwargs[key] = None
sid = transaction.savepoint()
with self.assertRaises(ValueError if key == 'author'
else IntegrityError):
# ForeignKeys throw a ValueError instead of IntegrityError.
Post.objects.create(**kwargs)
transaction.savepoint_rollback(sid)
示例2: update_or_add
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def update_or_add(self, **kwargs):
assert kwargs, 'update_or_add() must be passed at least one keyword argument'
defaults = kwargs.pop('defaults', {})
obj = get_first(self.filter(**kwargs))
result = (obj, False, True)
create = False
if not obj:
obj = self.model()
result = (obj, True, False)
create = True
try:
params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
params.update(defaults)
for attr, val in params.items():
if hasattr(obj, attr):
setattr(obj, attr, val)
sid = transaction.savepoint()
obj.save(force_update=not create)
if not create:
self.add(obj)
transaction.savepoint_commit(sid)
return result
except IntegrityError, e:
transaction.savepoint_rollback(sid)
示例3: bulk_insert
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def bulk_insert(cursor, variant_arch_id, rpm_id, content_category_id, sigkey_id, path_id):
sql = add_returning("""INSERT INTO %s (variant_arch_id, rpm_id, sigkey_id, content_category_id, path_id)
VALUES (%%s, %%s, %%s, %%s, %%s)""" % ComposeRPM._meta.db_table)
try:
sid = transaction.savepoint()
cursor.execute(sql, [variant_arch_id, rpm_id, sigkey_id, content_category_id, path_id])
if connection.features.can_return_id_from_insert:
insert_id = connection.ops.fetch_returned_insert_id(cursor)
else:
insert_id = connection.ops.last_insert_id(cursor, ComposeRPM._meta.db_table, "id")
except IntegrityError:
transaction.savepoint_rollback(sid)
cursor.execute("SELECT %s FROM %s WHERE variant_arch_id=%%s AND rpm_id=%%s"
% ("id", ComposeRPM._meta.db_table),
[variant_arch_id, rpm_id])
insert_id = int(cursor.fetchone()[0])
transaction.savepoint_commit(sid)
return insert_id
示例4: idempotent_transaction
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def idempotent_transaction(func):
if django.VERSION < (1, 7,) or django.VERSION >= (2, 0) and settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
return func
else:
@functools.wraps(func)
def func_wrapper(*args, **kwargs):
with transaction.atomic():
sp = transaction.savepoint()
try:
func(*args, **kwargs)
transaction.savepoint_rollback(sp)
except BaseException:
raise
return func_wrapper
示例5: is_valid
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def is_valid(self, raise_exception=False):
if not self.initial_data:
raise serializers.ValidationError({"inventory": "inventory empty"})
self._save_point = transaction.savepoint()
try:
current_project.clear_inventory()
self.clean_inventory_data(self.initial_data)
valid = super().is_valid(raise_exception=raise_exception)
except serializers.ValidationError as e:
transaction.savepoint_rollback(self._save_point)
raise e
if not valid:
transaction.savepoint_rollback(self._save_point)
return valid
示例6: test_missingfields
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def test_missingfields(self):
b = BugTracker.objects.create(baseurl=self.baseurl,
bt_type=self._get_type())
self.assertEqual(None, b.username)
self.assertEqual(None, b.password)
with self.assertRaises(IntegrityError):
sid = transaction.savepoint()
BugTracker.objects.create(baseurl=None,
bt_type=self._get_type())
transaction.savepoint_rollback(sid)
with self.assertRaises(IntegrityError):
BugTracker.objects.create(baseurl=self.baseurl)
示例7: compute_totals
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def compute_totals(self, request, pk=None):
"""
This works much like a regular PATCH, but rolls back the transaction
"""
validation_deserializer = ComplianceReportValidationSerializer(
data=request.data
)
if not validation_deserializer.is_valid():
return Response(validation_deserializer.errors)
sid = transaction.savepoint()
obj = self.get_object()
deserializer = ComplianceReportUpdateSerializer(
obj,
data=request.data,
partial=True,
context={'request': request}
)
deserializer.strip_summary = True
deserializer.disregard_status = True
if not deserializer.is_valid():
transaction.savepoint_rollback(sid)
return Response(deserializer.errors)
patched_obj = deserializer.save()
serializer = ComplianceReportDetailSerializer(patched_obj, context={'request': request})
result = serializer.data
transaction.savepoint_rollback(sid)
return Response(result)
示例8: update_or_create
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def update_or_create(self, **kwargs):
"""
updates, creates or gets based on the kwargs. Works like get_or_create but in addition will update
the kwargs specified in defaults and returns a third value to indicate if an update happened
:param kwargs:
:return:
"""
assert kwargs, 'update_or_create() must be passed at least one keyword argument'
obj, created = self.get_or_create(**kwargs)
defaults = kwargs.pop('defaults', {})
if created:
return obj, True, False
else:
try:
needs_save = False
params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
params.update(defaults)
for attr, val in params.items():
if hasattr(obj, attr):
setattr(obj, attr, val)
# sid = transaction.savepoint()
obj.save(force_update=True)
# transaction.savepoint_commit(sid)
return obj, False, True
except IntegrityError, e:
# transaction.savepoint_rollback(sid)
try:
return self.get(**kwargs), False, False
except self.model.DoesNotExist:
raise e
# Update the related instance or add it. The toMany equivalent to update_or_create
示例9: get_or_create
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def get_or_create(self, **kwargs):
"""
Looks up an object with the given kwargs, creating one if necessary.
Returns a tuple of (object, created), where created is a boolean
specifying whether an object was created.
"""
assert kwargs, \
'get_or_create() must be passed at least one keyword argument'
defaults = kwargs.pop('defaults', {})
lookup = kwargs.copy()
for f in self.model._meta.fields:
if f.attname in lookup:
lookup[f.name] = lookup.pop(f.attname)
try:
self._for_write = True
return self.get(**lookup), False
except self.model.DoesNotExist:
try:
params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
params.update(defaults)
obj = self.model(**params)
sid = transaction.savepoint(using=self.db)
obj.save(force_insert=True, using=self.db)
transaction.savepoint_commit(sid, using=self.db)
return obj, True
except IntegrityError as e:
transaction.savepoint_rollback(sid, using=self.db)
exc_info = sys.exc_info()
try:
return self.get(**lookup), False
except self.model.DoesNotExist:
# Re-raise the IntegrityError with its original traceback.
six.reraise(*exc_info)
示例10: transfer_money
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def transfer_money(_from, _to, quota):
if _from.money < 15:
raise ValueError("連手續費都付不起,請回吧!!")
_from.money = _from.money - 15
_from.save()
sid = transaction.savepoint()
try:
_from.money = _from.money - quota
if _from.money < 0:
raise ValueError("超額提領!")
_from.save()
_to.money = _to.money + quota
if _to.money > 100000:
raise ValueError("超額儲存!")
_to.save()
transaction.savepoint_commit(sid)
except ValueError as e:
logger.error("金額操作錯誤, 訊息:<{}>".format(e))
transaction.savepoint_rollback(sid)
except Exception as e:
logger.error("其他錯誤,訊息:<{}>".format(e))
transaction.savepoint_rollback(sid)
示例11: assertRaises
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def assertRaises(self, *args, **kwargs):
"""
Since we are expecting database errors, we must use savepoints in order
to make sure multiple errors can be caught in the same test case.
"""
sid = transaction.savepoint()
with super().assertRaises(*args, **kwargs):
yield
transaction.savepoint_rollback(sid)
示例12: bulk_insert
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def bulk_insert(cursor, rpm_nevra, filename, srpm_nevra=None,
srpm_commit_hash=None, srpm_commit_branch=None):
nvra = parse_nvra(rpm_nevra)
if srpm_nevra:
srpm_name = parse_nvra(srpm_nevra)["name"]
else:
srpm_name = nvra["name"]
sql = add_returning("""INSERT INTO %s (name, epoch, version, release, arch, srpm_nevra, srpm_name, filename, srpm_commit_hash, srpm_commit_branch)
VALUES (%%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s)""" % RPM._meta.db_table)
try:
sid = transaction.savepoint()
RPM.check_srpm_nevra(rpm_nevra, srpm_nevra)
cursor.execute(sql, [nvra["name"], nvra["epoch"], nvra["version"], nvra["release"],
nvra["arch"], srpm_nevra, srpm_name, filename, srpm_commit_hash,
srpm_commit_branch])
if connection.features.can_return_id_from_insert:
insert_id = connection.ops.fetch_returned_insert_id(cursor)
else:
insert_id = connection.ops.last_insert_id(cursor, RPM._meta.db_table, "id")
except (IntegrityError, ValidationError):
transaction.savepoint_rollback(sid)
cursor.execute("""SELECT %s FROM %s WHERE name=%%s AND epoch=%%s AND
version=%%s and release=%%s AND arch=%%s""" % ("id", RPM._meta.db_table),
[nvra["name"], nvra["epoch"], nvra["version"], nvra["release"], nvra["arch"]])
insert_id = int(cursor.fetchone()[0])
transaction.savepoint_commit(sid)
return insert_id
示例13: atomic
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def atomic(using=None):
sid = transaction.savepoint(using=using)
try:
yield
except IntegrityError:
transaction.savepoint_rollback(sid, using=using)
raise
else:
transaction.savepoint_commit(sid, using=using)
示例14: rollback
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import savepoint [as 别名]
def rollback():
"""Context manager that always rolls back to a savepoint.
This is useful when using hypothesis (https://hypothesis.readthedocs.org/)
which repeatedly runs tests to discover edge cases.
"""
sid = transaction.savepoint()
try:
yield
finally:
transaction.savepoint_rollback(sid)