Python django.db.transaction.set_rollback() Examples

The following are 14 code examples of django.db.transaction.set_rollback(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.transaction , or try the search function .
Example #1
Source File: testcases.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _rollback_atomics(cls, atomics):
        """Rollback atomic blocks opened through the previous method"""
        for db_name in reversed(cls._databases_names()):
            transaction.set_rollback(True, using=db_name)
            atomics[db_name].__exit__(None, None, None) 
Example #2
Source File: testcases.py    From bioforum with MIT License 5 votes vote down vote up
def _rollback_atomics(cls, atomics):
        """Rollback atomic blocks opened by the previous method."""
        for db_name in reversed(cls._databases_names()):
            transaction.set_rollback(True, using=db_name)
            atomics[db_name].__exit__(None, None, None) 
Example #3
Source File: testcases.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def _rollback_atomics(cls, atomics):
        """Rollback atomic blocks opened by the previous method."""
        for db_name in reversed(cls._databases_names()):
            transaction.set_rollback(True, using=db_name)
            atomics[db_name].__exit__(None, None, None) 
Example #4
Source File: testcases.py    From python with Apache License 2.0 5 votes vote down vote up
def _rollback_atomics(cls, atomics):
        """Rollback atomic blocks opened through the previous method"""
        for db_name in reversed(cls._databases_names()):
            transaction.set_rollback(True, using=db_name)
            atomics[db_name].__exit__(None, None, None) 
Example #5
Source File: test_sequences.py    From django-sequences with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_first_access_with_rollback(self):

        def one(output):
            output.append(('one', 'begin'))
            with transaction.atomic():
                value = get_next_value()
                output.append(('one', value))
                time.sleep(0.2)
                transaction.set_rollback(True)
                output.append(('one', 'rollback'))
            connection.close()

        def two(output):
            time.sleep(0.1)
            output.append(('two', 'begin'))
            with transaction.atomic():
                value = get_next_value()
                output.append(('two', value))
                output.append(('two', 'commit'))
            connection.close()

        expected = [
            ('one', 'begin'),
            ('one', 1),
            ('two', 'begin'),
            ('one', 'rollback'),
            ('two', 1),
            ('two', 'commit'),
        ]

        self.assertSequence(one, two, expected) 
Example #6
Source File: test_sequences.py    From django-sequences with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_later_access_with_rollback(self):

        get_next_value()

        def one(output):
            output.append(('one', 'begin'))
            with transaction.atomic():
                value = get_next_value()
                output.append(('one', value))
                time.sleep(0.2)
                transaction.set_rollback(True)
                output.append(('one', 'rollback'))
            connection.close()

        def two(output):
            time.sleep(0.1)
            output.append(('two', 'begin'))
            with transaction.atomic():
                value = get_next_value()
                output.append(('two', value))
                output.append(('two', 'commit'))
            connection.close()

        expected = [
            ('one', 'begin'),
            ('one', 2),
            ('two', 'begin'),
            ('one', 'rollback'),
            ('two', 2),
            ('two', 'commit'),
        ]

        self.assertSequence(one, two, expected) 
Example #7
Source File: testcases.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def _rollback_atomics(cls, atomics):
        """Rollback atomic blocks opened through the previous method"""
        for db_name in reversed(cls._databases_names()):
            transaction.set_rollback(True, using=db_name)
            atomics[db_name].__exit__(None, None, None) 
Example #8
Source File: testcases.py    From python2017 with MIT License 5 votes vote down vote up
def _rollback_atomics(cls, atomics):
        """Rollback atomic blocks opened through the previous method"""
        for db_name in reversed(cls._databases_names()):
            transaction.set_rollback(True, using=db_name)
            atomics[db_name].__exit__(None, None, None) 
Example #9
Source File: views.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def set_rollback():
    atomic_requests = connection.settings_dict.get('ATOMIC_REQUESTS', False)
    if atomic_requests and connection.in_atomic_block:
        transaction.set_rollback(True) 
Example #10
Source File: views.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.
    By default we handle the REST framework `APIException`, and also
    Django's built-in `Http404` and `PermissionDenied` exceptions.
    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'detail': exc.detail}

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)

    return None 
Example #11
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_ticket_11101(self):
        """Fixtures can be rolled back (ticket #11101)."""
        with transaction.atomic():
            management.call_command(
                'loaddata',
                'thingy.json',
                verbosity=0,
            )
            self.assertEqual(Thingy.objects.count(), 1)
            transaction.set_rollback(True)
        self.assertEqual(Thingy.objects.count(), 0) 
Example #12
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_ticket_11101(self):
        """Fixtures can be rolled back (ticket #11101)."""
        with transaction.atomic():
            management.call_command(
                'loaddata',
                'thingy.json',
                verbosity=0,
            )
            self.assertEqual(Thingy.objects.count(), 1)
            transaction.set_rollback(True)
        self.assertEqual(Thingy.objects.count(), 0) 
Example #13
Source File: compat.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def set_rollback():
    if hasattr(transaction, 'set_rollback'):
        if connection.settings_dict.get('ATOMIC_REQUESTS', False):
            # If running in >=1.6 then mark a rollback as required,
            # and allow it to be handled by Django.
            if connection.in_atomic_block:
                transaction.set_rollback(True)
    elif transaction.is_managed():
        # Otherwise handle it explicitly if in managed mode.
        if transaction.is_dirty():
            transaction.rollback()
        transaction.leave_transaction_management()
    else:
        # transaction not managed
        pass 
Example #14
Source File: middleware.py    From product-definition-center with MIT License 4 votes vote down vote up
def process_view(self, request, view_func, view_args, view_kwargs):
        user = None
        if request.user.is_authenticated:
            user = request.user

        if request.method == "GET":
            logger.debug("Start query request on the view %s." % view_func.__name__)
            # NOTE: We do not need create a changeset when we just SELECT somw records.
            response = view_func(request, *view_args, **view_kwargs)
        else:
            # trap the request and give response when the method is not defined in HTTP/1.1
            if request.method not in ["HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT", "PATCH", "OPTIONS"]:
                logger.error('Wrong method %s specified when calling %s', request.method.decode("utf-8"), request.path)
                response_data = json.dumps({"detail": 'Method "{method}" not allowed.'.format(method=request.method)},
                                           ensure_ascii=False)
                response = HttpResponse(response_data, content_type='application/json')
                response.status_code = status.HTTP_405_METHOD_NOT_ALLOWED
                return response

            logger.debug("Start write request on the view %s." % view_func.__name__)
            try:
                with transaction.atomic():
                    comment = request.META.get("HTTP_PDC_CHANGE_COMMENT", None)
                    request.changeset = models.Changeset(author=user, comment=comment)
                    request.changeset.requested_on = timezone.now()
                    response = view_func(request, *view_args, **view_kwargs)
                    # response.exception=True means there is an error occurs.
                    if getattr(response, 'exception', 0) or (
                        hasattr(response, 'status_code') and response.status_code >= 400
                    ):
                        # avoid recording changeset on server error, also
                        # abort the transaction so that no modifications are
                        # done to database
                        request.changeset.reset()
                        transaction.set_rollback(True)
                    else:
                        request.changeset.commit()
                        self._may_announce_big_change(request.changeset, request)
            except Exception:
                # NOTE: catch all errors that were raised by view.
                # And log the trace back to the file.
                logger.error('View Function Error: %s', request.path,
                             exc_info=sys.exc_info())
                # we do not want to break the default exception processing chains,
                # so re-raise the exception to the upper level.
                raise

        return response