当前位置: 首页>>代码示例>>Python>>正文


Python transaction.savepoint方法代码示例

本文整理汇总了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) 
开发者ID:chaoss,项目名称:prospector,代码行数:23,代码来源:tests.py

示例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) 
开发者ID:CalthorpeAnalytics,项目名称:urbanfootprint,代码行数:27,代码来源:geo_inheritance_manager.py

示例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 
开发者ID:product-definition-center,项目名称:product-definition-center,代码行数:21,代码来源:models.py

示例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 
开发者ID:plumdog,项目名称:django_migration_testcase,代码行数:16,代码来源:base.py

示例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 
开发者ID:KubeOperator,项目名称:KubeOperator,代码行数:16,代码来源:inventory.py

示例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) 
开发者ID:chaoss,项目名称:prospector,代码行数:16,代码来源:tests.py

示例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) 
开发者ID:bcgov,项目名称:tfrs,代码行数:34,代码来源:ComplianceReport.py

示例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 
开发者ID:CalthorpeAnalytics,项目名称:urbanfootprint,代码行数:34,代码来源:geo_inheritance_manager.py

示例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) 
开发者ID:blackye,项目名称:luscan-devel,代码行数:35,代码来源:query.py

示例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) 
开发者ID:its-django,项目名称:mysite,代码行数:28,代码来源:actions.py

示例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) 
开发者ID:lorinkoz,项目名称:django-pgschemas,代码行数:11,代码来源:test_tenants.py

示例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 
开发者ID:product-definition-center,项目名称:product-definition-center,代码行数:31,代码来源:models.py

示例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) 
开发者ID:thecodinghouse,项目名称:votes,代码行数:11,代码来源:compat.py

示例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) 
开发者ID:maas,项目名称:maas,代码行数:13,代码来源:orm.py


注:本文中的django.db.transaction.savepoint方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。