Python django.db.transaction.commit_on_success() Examples

The following are 6 code examples of django.db.transaction.commit_on_success(). 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: version_testing.py    From urbanfootprint with GNU General Public License v3.0 6 votes vote down vote up
def perform_updates(revision_manager, feature, associations, attribute, users):
    """
    Updates the feature to each value in the associations, where the associations are the
    instances stored at the given attribute
    :param feature:
    :param associations:
    :param attribute:
    :param users: users will be used for each save, round-robin style
    :return:
    """
    for i, association in enumerate(associations):
        with transaction.commit_on_success(), reversion.create_revision():
            setattr(feature, attribute, association)
            feature.updater = users[i % len(users)]
            feature.comment = "Comment %s" % association.id
            feature.approval_status = 'approved'
            feature.save()
            reversion.set_user(feature.updater)
            reversion.set_comment(feature.comment)
        version_list = revision_manager.get_unique_for_object(feature)
        version_count = len(version_list)
        assert version_count >= i, "Feature should have at least %s version but has %s" % (i, version_count) 
Example #2
Source File: admin.py    From crowdata with MIT License 5 votes vote down vote up
def add_documents_view(self, request, document_set_id):
        """ add a bunch of documents to
         a DocumentSet by uploading a CSV """
        document_set = get_object_or_404(self.model, pk=document_set_id)
        if request.FILES.get('csv_file'):
            # got a CSV, process, check and create
            csvreader = csv.reader(request.FILES.get('csv_file'))

            header_row = csvreader.next()
            if [h.strip() for h in header_row] != ['document_title', 'document_url']:
                messages.error(request,
                               _('Header cells must be document_title and document_url'))


            count = 0
            try:
                with transaction.commit_on_success():
                    for row in csvreader:
                        document_set.documents.create(name=row[0].strip(),
                                                      url=row[1].strip())
                        count += 1
            except:
                messages.error(request,
                               _('Could not create documents'))

                return redirect(reverse('admin:document_set_add_documents',
                                        args=(document_set_id,)))

            messages.info(request,
                          _('Successfully created %(count)d documents') % { 'count': count })

            return redirect(reverse('admin:crowdataapp_documentset_changelist'))

        else:
            return render_to_response('admin/document_set_add_documents.html',
                                      {
                                          'document_set': document_set,
                                          'current_app': self.admin_site.name,
                                      },
                                      RequestContext(request)) 
Example #3
Source File: db.py    From acacia_main with MIT License 5 votes vote down vote up
def save(self, must_create=False):
        """
        Saves the current session data to the database. If 'must_create' is
        True, a database error will be raised if the saving operation doesn't
        create a *new* entry (as opposed to possibly updating an existing
        entry).
        """
        obj = Session(
            session_key=self._get_or_create_session_key(),
            session_data=self.encode(self._get_session(no_load=must_create)),
            expire_date=self.get_expiry_date(),
            user_agent=self.user_agent,
            user_id=self.user_id,
            ip=self.ip,
        )
        using = router.db_for_write(Session, instance=obj)
        try:
            if django.VERSION >= (1, 6):
                with transaction.atomic(using):
                    obj.save(force_insert=must_create, using=using)
            else:
                with transaction.commit_on_success(using):
                    obj.save(force_insert=must_create, using=using)
        except IntegrityError as e:
            if must_create and 'session_key' in str(e):
                raise CreateError
            raise 
Example #4
Source File: views.py    From pedidosanonimos with MIT License 5 votes vote down vote up
def form_valid(self, form):
        context = self.get_context_data()
        esic_form = context['esic_form']

        if esic_form.is_valid():
            # TODO: Add transactionwith transaction.commit_on_success():
            esic_form.save()
            form.instance.esic = esic_form.instance
            self.object = form.save()

        return super(CreatePublicBodyView, self).form_valid(form) 
Example #5
Source File: revisionable_resource.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def save(self, bundle, skip_errors=False):
        """
            This is a copy of the parent method, but with the object save modified for versioning
        :param bundle:
        :param skip_errors:
        :return:
        """
        self.is_valid(bundle)

        if bundle.errors and not skip_errors:
            raise ImmediateHttpResponse(response=self.error_response(bundle.request, bundle.errors))

        # Check if they're authorized.
        if bundle.obj.pk:
            self.authorized_update_detail(self.get_object_list(bundle.request), bundle)
        else:
            self.authorized_create_detail(self.get_object_list(bundle.request), bundle)

        # Save FKs just in case.
        self.save_related(bundle)

        # Save the main object.
        with transaction.commit_on_success(), reversion.create_revision():
            bundle.obj.save()
            reversion.set_user(self.resolve_user(bundle.request.GET))
            reversion.set_comment(bundle.data['comment'] or '')  # Comment cannot be null

        bundle.objects_saved.add(self.create_identifier(bundle.obj))

        # Now pick up the M2M bits.
        m2m_bundle = self.hydrate_m2m(bundle)
        self.save_m2m(m2m_bundle)
        return bundle 
Example #6
Source File: merge_updater_tool.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def run_merge_tables(self, **kwargs):

        source_config_entity = self.config_entity
        target_config_entity = self.target_config_entity
        print ' source'
        print source_config_entity
        print ' target'
        print target_config_entity

        source_feature_class = source_config_entity.db_entity_feature_class(self.db_entity_key)
        source_db_entity = source_config_entity.db_entity_by_key(self.db_entity_key)
        #resolve the target table by looking at the import table of the source db_entity
        target_db_entity_key = source_db_entity.feature_class_configuration_as_dict.get('import_from_db_entity_key')
        target_feature_class = target_config_entity.db_entity_feature_class(target_db_entity_key)

        #filter the target features by their approval status
        source_features = source_feature_class.objects.filter(approval_status='approved')

        #iterate over the features and merge approved rows into the target table
        for source_feature in source_features:
            with transaction.commit_on_success(), reversion.create_revision():
                target_feature = target_feature_class.objects.get(id=source_feature.id)
                target_feature.__dict__.update(**source_feature.__dict__)
                target_feature.save()
                target_feature.comment = "Merge from ConfigEntity %s" % source_config_entity.key
                # If we have comments defined on the base table
                if hasattr(target_feature, 'comments'):
                    target_feature.comments = target_feature.comment
                reversion.set_user(self.updater)
                reversion.set_comment(target_feature.comment)

                #reset the approval field to null after changes are committed to the target
                source_feature.approval_status = None
                source_feature.save()


# TODO should be handled by based class but isn't