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


Python transaction.atomic方法代码示例

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


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

示例1: save

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def save(self, *args, **kwargs):
        """Save the model."""
        name_max_len = self._meta.get_field("name").max_length
        if len(self.name) > name_max_len:
            self.name = self.name[: (name_max_len - 3)] + "..."

        for _ in range(MAX_SLUG_RETRIES):
            try:
                # Attempt to save the model. It may fail due to slug conflict.
                with transaction.atomic():
                    super().save(*args, **kwargs)
                    break
            except IntegrityError as error:
                # Retry in case of slug conflicts.
                if "{}_slug".format(self._meta.db_table) in error.args[0]:
                    self.slug = None
                    continue

                raise
        else:
            raise IntegrityError(
                "Maximum number of retries exceeded during slug generation"
            ) 
开发者ID:genialis,项目名称:resolwe,代码行数:25,代码来源:base.py

示例2: _run

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def _run(anonymizer, objs):
    values = {}
    replacer_attr = tuple(r[0] for r in anonymizer.replacers)
    for obj in objs.iterator():
        retval = anonymizer.alter_object(obj)
        if retval is False:
            continue

        values[obj.pk] = {attname: getattr(obj, attname) for attname in replacer_attr}

    query = anonymizer.create_query(replacer_attr)
    query_args = anonymizer.create_query_args(values, replacer_attr)

    with transaction.atomic():
        with connection.cursor() as cursor:
            if connection.vendor == 'postgresql':
                cursor.execute('SET CONSTRAINTS ALL DEFERRED')
            cursor.executemany(query, query_args) 
开发者ID:BetterWorks,项目名称:django-anonymizer,代码行数:20,代码来源:base.py

示例3: toggle_source_tag

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def toggle_source_tag(request, evidence_id, source_id):
    """Toggle source tag for the given source and redirect to the evidence detail page for the associated evidence."""
    # May want to put in a sanity check here that source_id actually corresponds to evidence_id
    # Inefficient to have to do the DB lookup before making a modification. May want to have the client pass in
    # whether or not they're adding/removing the tag
    if request.method == 'POST':
        with transaction.atomic():
            source = get_object_or_404(EvidenceSource, pk=source_id)
            tag = EvidenceSourceTag.objects.get(tag_name=request.POST['tag'])
            user_tag = AnalystSourceTag.objects.filter(source=source, tagger=request.user, tag=tag)
            if user_tag.count() > 0:
                user_tag.delete()
                messages.success(request, _('Removed "{name}" tag from source.').format(name=tag.tag_name))
            else:
                AnalystSourceTag.objects.create(source=source, tagger=request.user, tag=tag)
                messages.success(request, _('Added "{name}" tag to source.').format(name=tag.tag_name))
            return HttpResponseRedirect(reverse('openach:evidence_detail', args=(evidence_id,)))
    else:
        # Redirect to the form where the user can toggle a source tag
        return HttpResponseRedirect(reverse('openach:evidence_detail', args=(evidence_id,))) 
开发者ID:twschiller,项目名称:open-synthesis,代码行数:22,代码来源:evidence.py

示例4: create_team

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def create_team(request):
    """Return a team creation view, or handle the form submission."""
    if request.method == 'POST':
        form = TeamCreateForm(request.POST)
        if form.is_valid():
            with transaction.atomic():
                team = form.save(commit=False)
                team.owner = request.user
                team.creator = request.user
                team.save()
                team.members.add(request.user)
                team.save()
            return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
    else:
        form = TeamCreateForm()
    return render(request, 'teams/create_team.html', {'form': form}) 
开发者ID:twschiller,项目名称:open-synthesis,代码行数:18,代码来源:teams.py

示例5: create_reminder_on

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def create_reminder_on(self, date, start_date, end_date):
        if start_date > date or date > end_date:
            # not timely, so ignore
            return

        if self.reminder_type == 'ROLE':
            roles = Role.objects_fresh.filter(unit=self.unit, role=self.role).select_related('person')
            recipients = [r.person for r in roles]
        elif self.reminder_type in ['PERS', 'INST']:
            recipients = [self.person]
        else:
            raise ValueError()

        for recip in recipients:
            ident = '%s_%s_%s' % (self.slug, recip.userid_or_emplid(), date.isoformat())
            # ident length: slug (50) + userid/emplid (9) + ISO date (10) + _ (2) <= 71
            rm = ReminderMessage(reminder=self, sent=False, date=date, person=recip, ident=ident)
            with transaction.atomic():
                try:
                    rm.save()
                except IntegrityError:
                    # already been created because we got IntegrityError on rm.ident
                    pass 
开发者ID:sfu-fas,项目名称:coursys,代码行数:25,代码来源:models.py

示例6: deduplicate

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def deduplicate(cls, start_date=None, end_date=None, dry_run=False):
        """
        Remove any EnrolmentHistory objects that aren't adding any new information.
        """
        all_ehs = EnrolmentHistory.objects.order_by('offering', 'date')
        if start_date:
            all_ehs = all_ehs.filter(date__gte=start_date)
        if end_date:
            all_ehs = all_ehs.filter(date__lte=end_date)

        for off_id, ehs in itertools.groupby(all_ehs, key=lambda eh: eh.offering_id):
            # iterate through EnrolmentHistory for this offering and purge any "same as yesterday" entries
            with transaction.atomic():
                current = next(ehs)
                for eh in ehs:
                    if current.is_dup(eh):
                        if not dry_run:
                            eh.delete()
                        else:
                            print('delete', eh)
                    else:
                        current = eh 
开发者ID:sfu-fas,项目名称:coursys,代码行数:24,代码来源:models.py

示例7: safely_delete

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def safely_delete(self):
        """
        Do the actions to safely "delete" the activity.
        """
        with transaction.atomic():
            # mangle name and short-name so instructors can delete and replace
            i = 1
            while True:
                suffix = "__%04i" % (i)
                existing = Activity.objects.filter(offering=self.offering, name=self.name+suffix).count() \
                        + Activity.objects.filter(offering=self.offering, short_name=self.short_name+suffix).count()
                if existing == 0:
                    break
                i += 1

            # update the activity
            self.deleted = True
            # Truncate the names if we need to since we are adding a 6 character suffix 
            self.name = self.name[:24] + suffix
            self.short_name = self.short_name[:9] + suffix
            self.slug = None
            self.save() 
开发者ID:sfu-fas,项目名称:coursys,代码行数:24,代码来源:models.py

示例8: post

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def post(self, request, cardid=None):
        data = JSONDeserializer().deserialize(request.body)
        if self.action == "update_card":
            if data:
                card = Card(data)
                card.save()
                return JSONResponse(card)

        if self.action == "reorder_cards":
            if "cards" in data and len(data["cards"]) > 0:
                with transaction.atomic():
                    for card_data in data["cards"]:
                        card = models.CardModel.objects.get(pk=card_data["id"])
                        card.sortorder = card_data["sortorder"]
                        card.save()
                return JSONResponse(data["cards"])

        return HttpResponseNotFound() 
开发者ID:archesproject,项目名称:arches,代码行数:20,代码来源:graph.py

示例9: delete

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def delete(self, request):
        mobile_survey_id = None
        try:
            mobile_survey_id = JSONDeserializer().deserialize(request.body)["id"]
        except Exception as e:
            logger.exception(e)

        try:
            connection_error = False
            with transaction.atomic():
                if mobile_survey_id is not None:
                    ret = MobileSurvey.objects.get(pk=mobile_survey_id)
                    ret.delete()
                    return JSONResponse({"success": True})
        except Exception as e:
            if connection_error is False:
                error_title = _("Unable to delete collector project")
                if "strerror" in e and e.strerror == "Connection refused" or "Connection refused" in e:
                    error_message = _("Unable to connect to CouchDB")
                else:
                    error_message = e.message
                connection_error = JSONResponse({"success": False, "message": error_message, "title": error_title}, status=500)
            return connection_error

        return HttpResponseNotFound() 
开发者ID:archesproject,项目名称:arches,代码行数:27,代码来源:mobile_survey.py

示例10: concept_value

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def concept_value(request):
    if request.method == "DELETE":
        data = JSONDeserializer().deserialize(request.body)

        if data:
            with transaction.atomic():
                value = ConceptValue(data)
                value.delete_index()
                value.delete()
                return JSONResponse(value)
    if request.method == "GET":
        valueid = request.GET.get("valueid")
        value = models.Value.objects.get(pk=valueid)
        return JSONResponse(value)

    return HttpResponseNotFound 
开发者ID:archesproject,项目名称:arches,代码行数:18,代码来源:concept.py

示例11: add_mapbox_layer

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def add_mapbox_layer(
        self, layer_name=False, mapbox_json_path=False, layer_icon="fa fa-globe", is_basemap=False,
    ):
        if layer_name is not False and mapbox_json_path is not False:
            with open(mapbox_json_path) as data_file:
                data = json.load(data_file)
                with transaction.atomic():
                    for layer in data["layers"]:
                        if "source" in layer:
                            layer["source"] = layer["source"] + "-" + layer_name
                    for source_name, source_dict in data["sources"].items():
                        map_source = models.MapSource.objects.get_or_create(name=source_name + "-" + layer_name, source=source_dict)
                    map_layer = models.MapLayer(
                        name=layer_name, layerdefinitions=data["layers"], isoverlay=(not is_basemap), icon=layer_icon
                    )
                    try:
                        map_layer.save()
                    except IntegrityError as e:
                        print("Cannot save layer: {0} already exists".format(layer_name)) 
开发者ID:archesproject,项目名称:arches,代码行数:21,代码来源:packages.py

示例12: perform_withdrawal

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def perform_withdrawal(self):
        with transaction.atomic():
            # Set the SeasonPlayer as inactive
            sp, _ = SeasonPlayer.objects.get_or_create(season=self.round.season, player=self.player)
            sp.is_active = False
            sp.save()

            # Delete pairings and give opponents byes
            for pairing in self.round.loneplayerpairing_set.filter(white=self.player):
                PlayerBye.objects.create(round=self.round, player=pairing.black,
                                         type='full-point-pairing-bye')
                pairing.delete()
            for pairing in self.round.loneplayerpairing_set.filter(black=self.player):
                PlayerBye.objects.create(round=self.round, player=pairing.white,
                                         type='full-point-pairing-bye')
                pairing.delete() 
开发者ID:cyanfish,项目名称:heltour,代码行数:18,代码来源:models.py

示例13: set_data_location

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def set_data_location(apps, schema_editor):
    """Create DataLocation for each Data."""
    Data = apps.get_model("flow", "Data")
    DataLocation = apps.get_model("flow", "DataLocation")

    for data in Data.objects.all():
        if os.path.isdir(
            os.path.join(settings.FLOW_EXECUTOR["DATA_DIR"], str(data.id))
        ):
            with transaction.atomic():
                # Manually set DataLocation id to preserve data directory.
                data_location = DataLocation.objects.create(
                    id=data.id, subpath=str(data.id)
                )
                data_location.data.add(data)

    # Increment DataLocation id's sequence
    if DataLocation.objects.exists():
        max_id = DataLocation.objects.order_by("id").last().id
        with connection.cursor() as cursor:
            cursor.execute(
                "ALTER SEQUENCE flow_datalocation_id_seq RESTART WITH {};".format(
                    max_id + 1
                )
            ) 
开发者ID:genialis,项目名称:resolwe,代码行数:27,代码来源:0028_add_data_location.py

示例14: delete_chunked

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def delete_chunked(queryset, chunk_size=500):
    """Chunked delete, which should be used if deleting many objects.

    The reason why this method is needed is that deleting a lot of Data objects
    requires Django to fetch all of them into memory (fast path is not used) and
    this causes huge memory usage (and possibly OOM).

    :param chunk_size: Optional chunk size
    """
    while True:
        # Discover primary key to limit the current chunk. This is required because delete
        # cannot be called on a sliced queryset due to ordering requirement.
        with transaction.atomic():
            # Get offset of last item (needed because it may be less than the chunk size).
            offset = queryset.order_by("pk")[:chunk_size].count()
            if not offset:
                break

            # Fetch primary key of last item and use it to delete the chunk.
            last_instance = queryset.order_by("pk")[offset - 1]
            queryset.filter(pk__lte=last_instance.pk).delete() 
开发者ID:genialis,项目名称:resolwe,代码行数:23,代码来源:base.py

示例15: process

# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def process(self, file_storage_id: Optional[int] = None):
        """Process objects to clean.

        When file_storage is not None process only that object.
        """
        logger.debug("Starting cleanup manager run")
        qset = FileStorage.objects.all()
        if file_storage_id is not None:
            qset = qset.filter(pk=file_storage_id)
        for file_storage in qset.filter(data__isnull=True).iterator():
            # Set applicable storage locations to deleting.
            StorageLocation.all_objects.unreferenced_locations().filter(
                file_storage=file_storage
            ).update(status=StorageLocation.STATUS_DELETING)
            with transaction.atomic():
                q_set = FileStorage.objects.filter(
                    id=file_storage.id
                ).select_for_update(skip_locked=True)
                # The FileStorage object is locked or deleted, skip processing.
                if not q_set.exists():
                    continue
                self._process_file_storage(q_set.first())

        logger.debug("Finished cleanup manager run") 
开发者ID:genialis,项目名称:resolwe,代码行数:26,代码来源:cleanup.py


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