Python django.db.transaction.rollback() Examples

The following are 13 code examples of django.db.transaction.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: testcase.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def _post_teardown(self):
        """Re-enable transaction methods, and roll back any changes.

        Rollback clears any DB changes made by the test so the original fixture
        data is again visible.

        """
        # Rollback any mutations made by tests:
        for db in self._databases():
            transaction.rollback(using=db)

        self._urlconf_teardown()

        # We do not need to close the connection here to prevent
        # http://code.djangoproject.com/ticket/7572, since we commit, not
        # rollback, the test fixtures and thus any cursor startup statements.

        # Don't call through to superclass, because that would call
        # _fixture_teardown() and close the connection. 
Example #2
Source File: transaction.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def process_response(self, request, response):
        """Commits and leaves transaction management."""
        if transaction.is_managed():
            if transaction.is_dirty():
                # Note: it is possible that the commit fails. If the reason is
                # closed connection or some similar reason, then there is
                # little hope to proceed nicely. However, in some cases (
                # deferred foreign key checks for exampl) it is still possible
                # to rollback().
                try:
                    transaction.commit()
                except Exception:
                    # If the rollback fails, the transaction state will be
                    # messed up. It doesn't matter, the connection will be set
                    # to clean state after the request finishes. And, we can't
                    # clean the state here properly even if we wanted to, the
                    # connection is in transaction but we can't rollback...
                    transaction.rollback()
                    transaction.leave_transaction_management()
                    raise
            transaction.leave_transaction_management()
        return response 
Example #3
Source File: tests.py    From django-seo2 with MIT License 6 votes vote down vote up
def test_uniqueness(self):
        # Check a path for uniqueness
        Coverage._meta.get_model('path').objects.create(_path="/unique/")
        try:
            Coverage._meta.get_model('path').objects.create(_path="/unique/")
            self.fail("Exception not raised when duplicate path created")
        except IntegrityError:
            transaction.rollback()

        # Check that uniqueness handles sites correctly
        current_site = Site.objects.get_current()
        another_site = Site.objects.create(id=current_site.id + 1)
        WithSites._meta.get_model('path').objects.create(_site=current_site,
                                                         _path="/unique/")
        WithSites._meta.get_model('path').objects.create(
            _site=another_site, _path="/unique/")
        try:
            WithSites._meta.get_model('path').objects.create(
                _site=current_site, _path="/unique/")
            self.fail("Exception not raised when duplicate path/site "
                      "combination created")
        except IntegrityError:
            transaction.rollback() 
Example #4
Source File: admin.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def edit_gsx_account(request, pk=None):
    object_list = GsxAccount.objects.all()
    title = GsxAccount._meta.verbose_name_plural

    if pk is None:
        act = GsxAccount()
    else:
        act = GsxAccount.objects.get(pk=pk)

    form = GsxAccountForm(instance=act)

    if request.method == 'POST':
        form = GsxAccountForm(request.POST, instance=act)
        if form.is_valid():
            try:
                act = form.save()
                cache.delete('gsx_session')
                try:
                    act.test()
                    messages.success(request, _(u'%s saved') % act.title)
                    return redirect(list_gsx_accounts)
                except gsxws.GsxError as e:
                    messages.warning(request, e)
            except IntegrityError:
                transaction.rollback()
                msg = _('GSX account for this sold-to and environment already exists')
                messages.error(request, msg)

    return render(request, 'admin/gsx/form.html', locals()) 
Example #5
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def xxx_rest_notes(request):
    """
    View to create new advisor notes via RESTful POST (json)
    """

    if request.method != 'POST':
        resp = HttpResponse(content='Only POST requests allowed', status=405)
        resp['Allow'] = 'POST'
        transaction.rollback()
        return resp

    if request.META['CONTENT_TYPE'] != 'application/json' and not request.META['CONTENT_TYPE'].startswith('application/json;'):
        transaction.rollback()
        return HttpResponse(content='Contents must be JSON (application/json)', status=415)

    try:
        rest.new_advisor_notes(request.body)
    except UnicodeDecodeError:
        transaction.rollback()
        return HttpResponse(content='Bad UTF-8 encoded text', status=400)
    except ValueError:
        transaction.rollback()
        return HttpResponse(content='Bad JSON in request body', status=400)
    except ValidationError as e:
        transaction.rollback()
        return HttpResponse(content=e.messages[0], status=422)
    except Exception as e:
        transaction.rollback()
        raise

    transaction.commit()
    return HttpResponse(status=200) 
Example #6
Source File: tests.py    From django-seo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_uniqueness(self):
        # Check a path for uniqueness
        Coverage._meta.get_model('path').objects.create(_path="/unique/")
        try:
            Coverage._meta.get_model('path').objects.create(_path="/unique/")
            self.fail("Exception not raised when duplicate path created")
        except IntegrityError:
            transaction.rollback()

        # Check that uniqueness handles sites correctly
        current_site = Site.objects.get_current()
        another_site = Site.objects.create(id=current_site.id + 1)
        WithSites._meta.get_model('path').objects.create(_site=current_site, _path="/unique/")
        pmd = WithSites._meta.get_model('path').objects.create(_site=another_site, _path="/unique/")
        try:
            WithSites._meta.get_model('path').objects.create(_site=current_site, _path="/unique/")
            self.fail("Exception not raised when duplicate path/site combination created")
        except IntegrityError:
            transaction.rollback()

        WithSubdomains._meta.get_model('path').objects.create(_subdomain='msk', title='Main page', _path='/')
        WithSubdomains._meta.get_model('path').objects.create(_subdomain='spb', title='Main page', _path='/')
        try:
            WithSubdomains._meta.get_model('path').objects.create(_subdomain='msk', title='Main page', _path='/')
            self.fail('Exception not raised when duplicate path/subdomain combination created')
        except IntegrityError:
            transaction.rollback() 
Example #7
Source File: dblock.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is None:
            transaction.commit()
        else:
            transaction.rollback()
        self.cursor.execute('UNLOCK TABLES')
        self.cursor.close() 
Example #8
Source File: views.py    From dirigible-spreadsheet with MIT License 5 votes vote down vote up
def rollback_on_exception(view):
    @wraps(view)
    def _rollback_on_exception(*args, **kwargs):
        transaction.set_autocommit(False)
        try:
            return view(*args, **kwargs)
        except:
            transaction.rollback()
            raise
        finally:
            transaction.set_autocommit(True)
    return _rollback_on_exception 
Example #9
Source File: transaction.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def process_exception(self, request, exception):
        """Rolls back the database and leaves transaction management"""
        if transaction.is_dirty():
            # This rollback might fail because of network failure for example.
            # If rollback isn't possible it is impossible to clean the
            # connection's state. So leave the connection in dirty state and
            # let request_finished signal deal with cleaning the connection.
            transaction.rollback()
        transaction.leave_transaction_management() 
Example #10
Source File: views.py    From bridge-adaptivity with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        """
        To Update activity by a POST request.

        Updating activity and changing the activity's order if activity changes the type.
        """
        activity = self.get_object()
        if request.POST.get("atype") != activity.atype:
            # NOTE(AndreyLykhoman): Excluding activity from atype group and reorder other activities. The autocommit
            #  was disabled in this part of code in order to send one query to DB.
            ordering_queryset = activity.get_ordering_queryset().exclude(pk=activity.pk)
            if ordering_queryset.exists():
                transaction.set_autocommit(False)
                try:
                    for index, element in enumerate(ordering_queryset):
                        element.order = index
                        element.save()
                except Exception:
                    transaction.rollback()
                    raise
                else:
                    transaction.commit()
                finally:
                    transaction.set_autocommit(True)
            # NOTE(AndreyLykhoman): Calculate a new activity's order
            new_order = 0
            tmp_activity = Activity.objects.filter(
                collection=activity.collection,
                atype=request.POST.get("atype")
            ).first()
            if tmp_activity:
                new_order = 1 + tmp_activity.get_ordering_queryset().latest('order').order

            activity.atype, activity.order = request.POST.get("atype"), new_order
            activity.save()
        result = super().post(request, *args, **kwargs)
        return result 
Example #11
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 #12
Source File: import_existing_notes_as_comments.py    From tfrs with Apache License 2.0 4 votes vote down vote up
def run(fallback_user_id=None):
    """For all credit trades having notes, create a new comment with the note text and the same
     creating user as the credit transfer.

     fallback_user_id will be used for credit_trades with no creating user.

     If it is not supplied, and such a trade is found, the script will rollback
     """
    transaction.set_autocommit(False)

    fallback_user = User.objects.filter(id=fallback_user_id).first()

    all_credit_trades_with_notes = CreditTrade.objects.filter(
        note__isnull=False
    ).all()

    count = 0

    for ct in all_credit_trades_with_notes:

        comment = CreditTradeComment()
        comment.credit_trade = ct
        comment.privileged_access = False

        comment.create_user = ct.create_user
        comment.create_timestamp = ct.create_timestamp
        comment.update_user = ct.update_user
        comment.update_timestamp = ct.update_timestamp

        if ct.create_user is None:
            if fallback_user is not None:
                comment.create_user = fallback_user
            else:
                transaction.rollback()
                raise Exception("Encountered a note with no create_user"
                                " and no fallback supplied")

        comment.comment = ct.note

        comment.save()

        ct.note = None
        ct.save()
        count += 1

    transaction.commit()

    print('imported {} notes'.format(count)) 
Example #13
Source File: views_api_0_1.py    From dirigible-spreadsheet with MIT License 4 votes vote down vote up
def calculate_and_get_json_for_api(request, username, sheet_id):
    sheet = get_object_or_404(Sheet, pk=sheet_id, owner__username=username)
    pads = None

    if request.method == 'POST':
        params = request.POST
    else:
        params = request.GET

    if 'api_key' in params:
        if not sheet.allow_json_api_access:
            transaction.rollback()
            return HttpResponseForbidden()
        elif params['api_key'] != sheet.api_key:
            transaction.rollback()
            return HttpResponseForbidden()
    elif 'dirigible_l337_private_key' in params:
        pads = OneTimePad.objects.filter(
            user=sheet.owner,
            guid=params['dirigible_l337_private_key']
        )
        too_old = datetime.now() - timedelta(36000)
        if len(pads) != 1 or pads[0].creation_time < too_old:
            transaction.rollback()
            return HttpResponseForbidden()
    else:
        transaction.rollback()
        return HttpResponseForbidden()

    worksheet = sheet.unjsonify_worksheet()
    for encoded_loc, new_formula in params.items():
        colrow = cell_ref_as_string_to_coordinates(encoded_loc)
        if colrow is not None:
            col, row = colrow
            worksheet.set_cell_formula(col, row, new_formula)
    sheet.jsonify_worksheet(worksheet)

    try:
        sheet.calculate()
        worksheet = sheet.unjsonify_worksheet()
        if worksheet._usercode_error:
            return HttpResponse(json.dumps({
                "usercode_error": {
                    "message": worksheet._usercode_error["message"],
                    "line": str(worksheet._usercode_error["line"])
                }
            }))
        response = HttpResponse(
            _sheet_to_value_only_json(sheet.name, worksheet))
        response['Access-Control-Allow-Origin'] = '*'
        return response
    except (Exception, HTTPError), e:
        return HttpResponse(str(e))