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


Python transaction.rollback方法代码示例

本文整理汇总了Python中django.db.transaction.rollback方法的典型用法代码示例。如果您正苦于以下问题:Python transaction.rollback方法的具体用法?Python transaction.rollback怎么用?Python transaction.rollback使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.db.transaction的用法示例。


在下文中一共展示了transaction.rollback方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _post_teardown

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import rollback [as 别名]
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. 
开发者ID:sfu-fas,项目名称:coursys,代码行数:21,代码来源:testcase.py

示例2: process_response

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import rollback [as 别名]
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 
开发者ID:blackye,项目名称:luscan-devel,代码行数:24,代码来源:transaction.py

示例3: test_uniqueness

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import rollback [as 别名]
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() 
开发者ID:romansalin,项目名称:django-seo2,代码行数:25,代码来源:tests.py

示例4: edit_gsx_account

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import rollback [as 别名]
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()) 
开发者ID:fpsw,项目名称:Servo,代码行数:31,代码来源:admin.py

示例5: xxx_rest_notes

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import rollback [as 别名]
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) 
开发者ID:sfu-fas,项目名称:coursys,代码行数:34,代码来源:views.py

示例6: test_uniqueness

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import rollback [as 别名]
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() 
开发者ID:whyflyru,项目名称:django-seo,代码行数:29,代码来源:tests.py

示例7: __exit__

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import rollback [as 别名]
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() 
开发者ID:DMOJ,项目名称:online-judge,代码行数:9,代码来源:dblock.py

示例8: rollback_on_exception

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import rollback [as 别名]
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 
开发者ID:pythonanywhere,项目名称:dirigible-spreadsheet,代码行数:14,代码来源:views.py

示例9: process_exception

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import rollback [as 别名]
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() 
开发者ID:blackye,项目名称:luscan-devel,代码行数:11,代码来源:transaction.py

示例10: post

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import rollback [as 别名]
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 
开发者ID:harvard-vpal,项目名称:bridge-adaptivity,代码行数:39,代码来源:views.py

示例11: set_rollback

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import rollback [as 别名]
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 
开发者ID:erigones,项目名称:esdc-ce,代码行数:17,代码来源:compat.py

示例12: run

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import rollback [as 别名]
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)) 
开发者ID:bcgov,项目名称:tfrs,代码行数:50,代码来源:import_existing_notes_as_comments.py

示例13: calculate_and_get_json_for_api

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import rollback [as 别名]
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)) 
开发者ID:pythonanywhere,项目名称:dirigible-spreadsheet,代码行数:55,代码来源:views_api_0_1.py


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