Python django.db.transaction.commit() Examples

The following are 30 code examples of django.db.transaction.commit(). 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: 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 #2
Source File: clone.py    From django-tenants with MIT License 6 votes vote down vote up
def clone_schema(self, base_schema_name, new_schema_name, set_connection=True):
        """
        Creates a new schema `new_schema_name` as a clone of an existing schema
        `old_schema_name`.
        """
        if set_connection:
            connection.set_schema_to_public()
        cursor = connection.cursor()

        # check if the clone_schema function already exists in the db
        try:
            cursor.execute("SELECT 'clone_schema'::regproc")
        except ProgrammingError:
            self._create_clone_schema_function()
            transaction.commit()

        if schema_exists(new_schema_name):
            raise ValidationError("New schema name already exists")

        sql = 'SELECT clone_schema(%(base_schema)s, %(new_schema)s, true, false)'
        cursor.execute(
            sql,
            {'base_schema': base_schema_name, 'new_schema': new_schema_name}
        )
        cursor.close() 
Example #3
Source File: populate_competitors.py    From fairtest with Apache License 2.0 6 votes vote down vote up
def _populate_stores(self, filename):
        "Open and parse a csv file, and register stores"
        try:
            f = open(filename)
        except IOError as error:
            print("I/O error while opening file: <%s>" % filename,\
                    file=sys.stderr)
            return

        for line in f:
            try:
                line = line.split('\n')[0]
                if line[0] == '#':
                    continue
                zipcode = str(line.split(',')[1])
                latitude = float(line.split(',')[2])
                longitude = float(line.split(',')[3])
            except IndexError as error:
                print("Malformed line: <%s>" % line, file=sys.stderr)
                continue
            c = Competitor(zipcode, latitude, longitude)
            c.save()
            print("Store:%s saved"% (zipcode))
        transaction.commit()
        f.close() 
Example #4
Source File: populate_stores.py    From fairtest with Apache License 2.0 6 votes vote down vote up
def _populate_stores(self, filename):
        "Open and parse a csv file, and register stores"
        try:
            f = open(filename)
        except IOError as error:
            print("I/O error while opening file: <%s>" % filename,\
                    file=sys.stderr)
            return

        for line in f:
            try:
                line = line.split('\n')[0]
                if line[0] == '#':
                    continue
                zipcode = str(line.split(',')[0])
                latitude = float(line.split(',')[1])
                longitude = float(line.split(',')[2])
            except IndexError as error:
                print("Malformed line: <%s>" % line, file=sys.stderr)
                continue
            s = Store(zipcode, latitude, longitude)
            s.save()
            print("Store:%s saved"% (zipcode))
        transaction.commit()
        f.close() 
Example #5
Source File: populate_zipcodes.py    From fairtest with Apache License 2.0 6 votes vote down vote up
def _populate_zipcodes(self, filename):
        "Open and parse a csv file, and register zipcodes"
        try:
            f = open(filename)
        except IOError as error:
            print("I/O error while opening file: <%s>" % filename,\
                    file=sys.stderr)
            return

        for line in f:
            try:
                line = line.split('\n')[0]
                if line[0] == '#':
                    continue
                zipcode = str(line.split(',')[0])
                latitude = float(line.split(',')[3])
                longitude = float(line.split(',')[4])
            except IndexError as error:
                print("Malformed line: <%s>" % line, file=sys.stderr)
                continue
            u = Zipcode(zipcode, latitude, longitude)
            u.save()
            print("Zipcode:%s saved" % (zipcode))
        transaction.commit()
        f.close() 
Example #6
Source File: facade_v1.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def remove_pool_members(id_pool_member_noempty, sp, user):
    # exclue server pool member
    del_smp = sp.serverpoolmember_set.exclude(id__in=id_pool_member_noempty)
    if del_smp:
        for obj in del_smp:

            obj.delete()

            # execute script remove real if pool already created
            # commit transaction after each successful script call
            if sp.pool_created:
                command = settings.POOL_REAL_REMOVE % (
                    obj.server_pool_id, obj.ip_id if obj.ip else obj.ipv6_id, obj.port_real)
                code, _, _ = exec_script(command)
                if code != 0:
                    raise exceptions.ScriptCreatePoolException()
                transaction.commit() 
Example #7
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 #8
Source File: test_views_api_0_1.py    From dirigible-spreadsheet with MIT License 6 votes vote down vote up
def test_rolls_back_and_reraises_if_get_object_raises_with_uncommitted_changes(
        self, mock_get_object_or_404
    ):
        try:
            # django.test.TestCase replaces the transaction management functions with nops,
            # which is generally useful but breaks this test, as we're checking that the
            # exception we raise isn't masked by one in the leave_transaction_management
            # saying that there was a pending commit/rollback when the view returned.
            restore_transaction_methods()
            transaction.commit()

            expected_exception = Exception("Expected exception")
            def set_dirty_and_raise_exception(*args, **kwargs):
                transaction.set_dirty()
                raise expected_exception
            mock_get_object_or_404.side_effect = set_dirty_and_raise_exception

            try:
                calculate_and_get_json_for_api(self.request, self.user.username, self.sheet.id)
            except Exception, e:
                self.assertEquals(e, expected_exception)
            else: 
Example #9
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def email_alert( request, alert_type, alert_id ):
    alert = get_object_or_404(Alert, id=alert_id, alerttype__unit__in=request.units)
    
    if request.method == 'POST':
        form = EmailResolutionForm(request.POST)
        if form.is_valid():
            f = form.save(commit=False)
            f.alert = alert
            f.update_type = "EMAI"
            f.save()
            messages.success(request, "Emailed student and resolved alert %s." % str(alert) )
            
            l = LogEntry(userid=request.user.username,
                  description="Resolved alert %s." % str(alert),
                  related_object=form.instance)
            l.save()            
            
            send_mail( form.cleaned_data['subject'], f.comments, form.cleaned_data['from_email'], [form.cleaned_data['to_email']] )
            return HttpResponseRedirect(reverse('alerts.views.view_alert', kwargs={'alert_type':alert_type, 'alert_id':alert_id}))
    else:
        form = EmailResolutionForm(initial={'resolved_until': datetime.date.today(), 'to_email': alert.person.email(), 'from_email': request.user.email})
    
    return render(request, 'alerts/email_alert.html', { 'alert_type':alert.alerttype, 
                                                          'alert':alert,
                                                          'form': form }) 
Example #10
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def reopen_or_comment_alert( request, alert_type, alert_id, update_code, wording):
    alert = get_object_or_404(Alert, id=alert_id, alerttype__unit__in=request.units)
    
    if request.method == 'POST':
        form = AlertUpdateForm(request.POST)
        if form.is_valid():
            f = form.save(commit=False)
            f.alert = alert
            f.update_type = update_code
            f.save()
            messages.success(request, "Updated alert %s." % str(alert) )
            l = LogEntry(userid=request.user.username,
                  description="Updated alert %s." % str(alert),
                  related_object=form.instance)
            l.save()            
            return HttpResponseRedirect(reverse('alerts.views.view_alert', kwargs={'alert_type':alert_type, 'alert_id':alert_id}))
    else:
        form = AlertUpdateForm()
    
    return render(request, 'alerts/resolve_alert.html', { 'alert_type':alert.alerttype, 
                                                          'alert':alert,
                                                          'form': form,
                                                          'resolve_reopen_or_comment_on': wording}) 
Example #11
Source File: test_views_api_0_1.py    From dirigible-spreadsheet with MIT License 6 votes vote down vote up
def test_commits_transaction_even_on_sheet_calculate_exception(
        self, mock_get_object, mock_transaction
    ):
        mock_sheet = mock_get_object.return_value
        mock_sheet.calculate = self.die
        mock_sheet.owner = self.user
        mock_sheet.allow_json_api_access = True
        self.request.method = 'POST'
        self.request.POST['api_key'] = mock_sheet.api_key = 'key'

        actual = calculate_and_get_json_for_api(
            self.request, self.user.username, self.sheet.id)

        self.assertCalledOnce(mock_transaction.commit)
        self.assertTrue(isinstance(actual, HttpResponse))
        self.assertEquals(actual.content, 'should not be called') 
Example #12
Source File: deletion.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def force_managed(func):
    @wraps(func)
    def decorated(self, *args, **kwargs):
        if not transaction.is_managed(using=self.using):
            transaction.enter_transaction_management(using=self.using)
            forced_managed = True
        else:
            forced_managed = False
        try:
            func(self, *args, **kwargs)
            if forced_managed:
                transaction.commit(using=self.using)
            else:
                transaction.commit_unless_managed(using=self.using)
        finally:
            if forced_managed:
                transaction.leave_transaction_management(using=self.using)
    return decorated 
Example #13
Source File: utils.py    From django-pgschemas with MIT License 6 votes vote down vote up
def clone_schema(base_schema_name, new_schema_name, dry_run=False):
    """
    Creates a new schema ``new_schema_name`` as a clone of an existing schema
    ``base_schema_name``.
    """
    check_schema_name(new_schema_name)
    cursor = connection.cursor()

    # check if the clone_schema function already exists in the db
    try:
        cursor.execute("SELECT 'clone_schema'::regproc")
    except ProgrammingError:  # pragma: no cover
        _create_clone_schema_function()
        transaction.commit()

    try:
        with transaction.atomic():
            sql = "SELECT clone_schema(%(base_schema)s, %(new_schema)s, TRUE)"
            cursor.execute(sql, {"base_schema": base_schema_name, "new_schema": new_schema_name})
            cursor.close()
            if dry_run:
                raise DryRunException
    except DryRunException:
        cursor.close() 
Example #14
Source File: RequestVipRealEditResource.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def remove_reals_after_script(port_vip, ip_type, vip, port_real, priority, weight, id_ip, user):
    """
        Remove real in VIP if script was completed successfully.
        The script access the db when is executing.
        This method is called if code returns 0.
    """

    server_pool = ServerPool.objects.get(
        vipporttopool__port_vip=port_vip, vipporttopool__requisicao_vip=vip)
    if ip_type == IP_VERSION.IPv4[1]:
        server_pool_member = ServerPoolMember.objects.get(server_pool=server_pool,
                                                          port_real=port_real,
                                                          priority=priority,
                                                          weight=weight,
                                                          ip=id_ip)
    else:
        server_pool_member = ServerPoolMember.objects.get(server_pool=server_pool,
                                                          port_real=port_real,
                                                          priority=priority,
                                                          weight=weight,
                                                          ipv6=id_ip)
    server_pool_member.delete()
    transaction.commit() 
Example #15
Source File: prune_database.py    From trunk-player with MIT License 6 votes vote down vote up
def purge_trans(options):

    days_opt = options['days']
    days_default = False
    if days_opt == -1:
        days_opt = 0
        days_default = True

    t = Transmission.objects.filter(start_datetime__lt=timezone.now() - timedelta(days=days_opt))
    print('Pruning %s transmissions older than %s days.' % (t.count(), days_opt))
    t.delete()
    print('Pruning complete')
    if 'sqlite' in db_engine:
        def vacuum_db(using='default'):
            cursor = connections[using].cursor()
            cursor.execute("VACUUM")
            transaction.commit()

        print ("Vacuuming database...")
        before = os.stat(db_name).st_size
        print ("Size before: %s bytes" % before)
        vacuum_db()
        after = os.stat(db_name).st_size
        print ("Size after: %s bytes" % after)
        print ("Reclaimed: %s bytes" % (before - after)) 
Example #16
Source File: models.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def deactivate(self, authenticated_user, commit=False):
        """
            Update status column  to 'active = 0'
            @param authenticated_user: User authenticate
            @raise NetworkIPv6Error: Error disabling NetworkIPv6.
        """

        try:

            self.active = 0
            self.save(authenticated_user, commit=commit)

            net_slz = get_app('api_network', 'serializers.v3')

            serializer = net_slz.NetworkIPv6V3Serializer(
                self,
                include=('vlan__details__environment__basic',))

            data_to_queue = serializer.data
            data_to_queue.update({
                'description': queue_keys.NETWORKv6_DEACTIVATE
            })

            # Send to Queue
            queue_manager = QueueManager(broker_vhost='tasks',
                                         queue_name='tasks.aclapi',
                                         exchange_name='tasks.aclapi',
                                         routing_key='tasks.aclapi')
            queue_manager.append({
                'action': queue_keys.NETWORKv6_DEACTIVATE,
                'kind': queue_keys.NETWORKv6_KEY,
                'data': data_to_queue
            })
            queue_manager.send()
        except Exception, e:
            self.log.error(u'Error disabling NetworkIPv6.')
            raise NetworkIPv6Error(e, u'Error disabling NetworkIPv6.') 
Example #17
Source File: models.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def deactivate(self, authenticated_user, commit=False):
        """
            Update status column  to 'active = 0'
            @param authenticated_user: User authenticate
            @raise NetworkIPv4Error: Error disabling a NetworkIPv4.
        """

        from networkapi.api_network.serializers.v1 import NetworkIPv4Serializer

        try:

            self.active = 0
            # Send to Queue
            queue_manager = QueueManager(broker_vhost='tasks',
                                         queue_name='tasks.aclapi',
                                         exchange_name='tasks.aclapi',
                                         routing_key='tasks.aclapi')
            serializer = NetworkIPv4Serializer(self)
            data_to_queue = serializer.data
            data_to_queue.update({
                'description': queue_keys.NETWORKv4_DEACTIVATE})
            queue_manager.append({
                'action': queue_keys.NETWORKv4_DEACTIVATE,
                'kind': queue_keys.NETWORKv4_KEY,
                'data': data_to_queue})
            queue_manager.send()
            self.save(authenticated_user, commit=commit)

        except Exception, e:
            self.log.error(u'Error disabling NetworkIPv4.')
            raise NetworkIPv4Error(e, u'Error disabling NetworkIPv4.') 
Example #18
Source File: publishing.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def _post_save_publishing(job, config_entity, user, **kwargs):
    """
        Runs all configured publishers via the Django signals they depend upon.
        This is done in Celery in order to support long running tasks launched from a client.
        Peer tasks are run in parallel. Dependent tasks are called after the tasks they depend on complete

    :param hash_id: Job hash id
    :param config_entity:
    :param user: The current user or None if no user is in scope
    :return:
    """

    if not settings.FOOTPRINT_INIT:
        # There is a poorly-understood issue related to uploading .gdb
        # files with mutliple layers (possibly caused by some race
        # condition) that, without sleeping here, causes the celery
        # task to run without an `instance` (the object that triggered
        # post save processing). Testing had shown 10 seconds to be the
        # shortest amount of time to wait here that permits the post-save
        # processing to complete successfully.
        time.sleep(10)

    bundle = kwargs['bundle']
    # Make sure all the Feature subclasses that the celery worker might need are created
    if config_entity:
        config_entity._feature_classes_created = False
        FeatureClassCreator(config_entity)

    # Get the publisher_name, proportion, and signal_path
    publishing_info = get_publishing_info(**kwargs)

    try:
        # Make sure no transactions are outstanding
        # This shoudln't be needed once Django is upgraded
        transaction.commit()
    except Exception, e:
        pass

    # Updated the kwargs to include the resolved instance. This will be sent when we recurse on post_save_publishing
    # Also use first=False to indicate recursion so we don't resend the start signal to the client 
Example #19
Source File: v1.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def deploy_networkIPv6_configuration(user, networkipv6, equipment_list):
    """Loads template for creating Network IPv6 equipment configuration, creates file and
    apply config.

    Args: NetworkIPv6 object
    Equipamento objects list

    Returns: List with status of equipments output
    """

    data = dict()
    # lock network id to prevent multiple requests to same id
    with distributedlock(LOCK_NETWORK_IPV6 % networkipv6.id):
        with distributedlock(LOCK_VLAN % networkipv6.vlan.id):
            if networkipv6.active == 1:
                data['output'] = 'Network already active. Nothing to do.'
                return data

            # load dict with all equipment attributes
            dict_ips = get_dict_v6_to_use_in_configuration_deploy(
                user, networkipv6, equipment_list)
            status_deploy = dict()
            # TODO implement threads
            for equipment in equipment_list:
                # generate config file
                file_to_deploy = _generate_config_file(
                    dict_ips, equipment, TEMPLATE_NETWORKv6_ACTIVATE)
                # deploy config file in equipments
                lockvar = LOCK_EQUIPMENT_DEPLOY_CONFIG_NETWORK_SCRIPT % (
                    equipment.id)
                status_deploy[equipment.id] = deploy_config_in_equipment_synchronous(
                    file_to_deploy, equipment, lockvar)

            networkipv6.activate(user)
            transaction.commit()
            if networkipv6.vlan.ativada == 0:
                networkipv6.vlan.activate(user)

            return status_deploy 
Example #20
Source File: RequestVipsRealResource.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def rollback_changes(self, operation, new_call, network_version, vip_id, ip_id, port_real, port_vip, real_name, end_ip, user):
        if (operation == 'add'):  # So remove the item that was inserted
            if IP_VERSION.IPv4[0] == network_version:
                if IP_VERSION.IPv4[0] == network_version:
                    if new_call:
                        pool_members = ServerPoolMember.objects.filter(
                            ip=ip_id, server_pool__vipporttopool__requisicao_vip__id=vip_id, server_pool__vipporttopool__port_vip=port_vip, port_real=port_real)
                        [pool_member.delete()
                         for pool_member in pool_members]
                    else:
                        pool_members = ServerPoolMember.objects.filter(
                            ip=ip_id, server_pool__vipporttopool__requisicao_vip__id=vip_id)
                        [pool_member.delete()
                         for pool_member in pool_members]
                else:
                    if new_call:
                        pool_members = ServerPoolMember.objects.filter(
                            ipv6=ip_id, server_pool__vipporttopool__requisicao_vip__id=vip_id, server_pool__vipporttopool__port_vip=port_vip, port_real=port_real)
                        [pool_member.delete()
                         for pool_member in pool_members]
                    else:
                        pool_members = ServerPoolMember.objects.filter(
                            ipv6=ip_id, server_pool__vipporttopool__requisicao_vip__id=vip_id)
                        [pool_member.delete()
                         for pool_member in pool_members]
            # commit to rollback when script return error
            transaction.commit() 
Example #21
Source File: test_timestampedmodel.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_updated_is_updated_when_object_saved(self):
        obj = TimestampedModelTestModel()
        obj.save()
        old_updated = obj.updated
        transaction.commit()
        obj.save()
        self.assertLessEqual(old_updated, obj.updated) 
Example #22
Source File: BaseModel.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def save(self, user=None, force_insert=False, force_update=False, commit=False, **kwargs):
        if user:
            self.set_authenticated_user(user)
        super(BaseModel, self).save(force_insert, force_update, **kwargs)
        if commit is True:
            transaction.commit() 
Example #23
Source File: facade_v1.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def update_pool_maxconn(maxconn, old_maxconn, sp, user):
    sp.default_limit = maxconn
    sp.save()

    # If pool member  exists, checks if all of them have the same maxconn
    # before changing its default maxconn
    if(len(sp.serverpoolmember_set.all()) > 0):
        if(old_maxconn != sp.default_limit and sp.pool_created):

            for serverpoolmember in sp.serverpoolmember_set.all():
                if serverpoolmember.limit != old_maxconn:
                    raise exceptions.ScriptAlterLimitPoolDiffMembersException()
                else:
                    serverpoolmember.limit = maxconn
                    serverpoolmember.save()

            transaction.commit()
            command = settings.POOL_MANAGEMENT_LIMITS % (sp.id)
            code, _, _ = exec_script(command)
            if code != 0:
                sp.default_limit = old_maxconn
                for serverpoolmember in sp.serverpoolmember_set.all():
                    serverpoolmember.limit = old_maxconn
                    serverpoolmember.save()

                sp.save()
                transaction.commit()
                raise exceptions.ScriptAlterLimitPoolException() 
Example #24
Source File: facade_v1.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def apply_health_check(hc, old_healthcheck, sp, user):
    # Applies new healthcheck in pool
    sp.healthcheck = hc
    sp.save()
    if (old_healthcheck.id != hc.id and sp.pool_created):
        transaction.commit()
        command = settings.POOL_HEALTHCHECK % (sp.id)
        code, _, _ = exec_script(command)
        if code != 0:
            sp.healthcheck = old_healthcheck
            sp.save()
            transaction.commit()
            raise exceptions.ScriptCreatePoolException() 
Example #25
Source File: facade_v1.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def update_load_balancing_method(balancing, old_lb_method, sp, user):
    sp.lb_method = balancing
    sp.save()
    if (old_lb_method != sp.lb_method and sp.pool_created):
        transaction.commit()
        command = settings.POOL_MANAGEMENT_LB_METHOD % (sp.id)
        code, _, _ = exec_script(command)
        if code != 0:
            sp.lb_method = old_lb_method
            sp.save()
            transaction.commit()
            raise exceptions.ScriptCreatePoolException() 
Example #26
Source File: facade_v1.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def deploy_pool_member_config(id_ip, id_pool, port_ip, spm, user):
    transaction.commit()
    # def prepare_and_save(self, server_pool, ip, ip_type, priority, weight, port_real, user, commit=False):
    # spm.prepare_and_save(sp, ip_object, IP_VERSION.IPv4[1], dic['priority'], dic['weight'], dic['port_real'], user, True)
    command = settings.POOL_REAL_CREATE % (id_pool, id_ip, port_ip)
    code, _, _ = exec_script(command)
    if code != 0:
        spm.delete()
        transaction.commit()
        raise exceptions.ScriptCreatePoolException()

        # if sp.healthcheck_id:
        #    spm.healthcheck = sp.healthcheck 
Example #27
Source File: facade_v1.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def apply_priorities(list_pool_member, old_priorities_list, sp, user):
    transaction.commit()
    command = settings.POOL_MEMBER_PRIORITIES % (sp.id)
    code, _, _ = exec_script(command)
    if code != 0:
        for i in range(0, len(old_priorities_list)):
            list_pool_member[i].priority = old_priorities_list[i]
            list_pool_member[i].save()
        transaction.commit()
        raise exceptions.ScriptAlterPriorityPoolMembersException() 
Example #28
Source File: query.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def update(self, **kwargs):
        """
        Updates all elements in the current QuerySet, setting all the given
        fields to the appropriate values.
        """
        assert self.query.can_filter(), \
                "Cannot update a query once a slice has been taken."
        self._for_write = True
        query = self.query.clone(sql.UpdateQuery)
        query.add_update_values(kwargs)
        if not transaction.is_managed(using=self.db):
            transaction.enter_transaction_management(using=self.db)
            forced_managed = True
        else:
            forced_managed = False
        try:
            rows = query.get_compiler(self.db).execute_sql(None)
            if forced_managed:
                transaction.commit(using=self.db)
            else:
                transaction.commit_unless_managed(using=self.db)
        finally:
            if forced_managed:
                transaction.leave_transaction_management(using=self.db)
        self._result_cache = None
        return rows 
Example #29
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 #30
Source File: test_timestampedmodel.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_created_bracketed_by_before_and_after_time(self):
        before = now()
        obj = TimestampedModelTestModel()
        obj.save()
        transaction.commit()
        after = now()
        self.assertLessEqual(before, obj.created)
        self.assertGreaterEqual(after, obj.created)