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


Python attributes.flag_modified函数代码示例

本文整理汇总了Python中sqlalchemy.orm.attributes.flag_modified函数的典型用法代码示例。如果您正苦于以下问题:Python flag_modified函数的具体用法?Python flag_modified怎么用?Python flag_modified使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: add_image_size

def add_image_size(context):
    images = FileCollection(context.session, type='image')

    for image in images.query():
        if not hasattr(image.reference, 'size'):

            # potentially dangerous and might not work with other storage
            # providers, so don't reuse unless you are sure about the
            # consequences
            image.reference._thaw()

            if image.reference.content_type == 'image/svg+xml':
                image.reference.size = get_svg_size_or_default(
                    image.reference.file
                )
            else:
                image.reference.size = get_image_size(
                    Image.open(image.reference.file)
                )

                thumbnail_metadata = copy(image.reference.thumbnail_small)
                thumbnail_metadata['size'] = get_image_size(
                    Image.open(
                        context.app.bound_depot.get(
                            image.get_thumbnail_id(size='small')
                        )
                    )
                )

                image.reference.thumbnail_small = thumbnail_metadata

            flag_modified(image, 'reference')
开发者ID:OneGov,项目名称:onegov.file,代码行数:32,代码来源:upgrade.py

示例2: edit

    def edit(self, pid=None):
        """Edit deposit."""
        pid = pid or self.pid

        def _edit(record):
            """Update selected keys."""
            data = record.dumps()
            # Keep current record revision for merging.
            data['_deposit']['pid']['revision_id'] = record.revision_id
            data['_deposit']['status'] = 'draft'
            data['$schema'] = self.build_deposit_schema(record)
            return data

        with db.session.begin_nested():
            before_record_update.send(self)

            record_pid, record = self.fetch_published()
            assert PIDStatus.REGISTERED == record_pid.status
            assert record['_deposit'] == self['_deposit']

            self.model.json = _edit(record)

            flag_modified(self.model, 'json')
            db.session.merge(self.model)

        after_record_update.send(self)
        return self.__class__(self.model.json, model=self.model)
开发者ID:nharraud,项目名称:invenio-deposit,代码行数:27,代码来源:api.py

示例3: set_setting

    def set_setting(self, key, value):
        if key not in org_settings:
            raise KeyError(key)

        self.settings.setdefault('settings', {})
        self.settings['settings'][key] = value
        flag_modified(self, 'settings')
开发者ID:getredash,项目名称:redash,代码行数:7,代码来源:organizations.py

示例4: gain_xp

	def gain_xp (self, xp):
		rules = self.game_session.rules

		sum_xp = self.xp + xp
		new_level = rules.get_level(sum_xp)
		if new_level is None:
			# TODO: log error
			return

		self.xp = sum_xp

		# Level up?
		level_diff = new_level - self.level
		for i in range(0, level_diff):
			level_info = rules.get_level_info(self.level + 1)
			if not level_info:
				break # TODO: WTF?
			self.level += 1

			# inc skills
			for cat_id, _formula in level_info.get('skills_categories_formulas', {}).iteritems():
				self.skill_points.setdefault(cat_id, 0)
				points_gained = formula.FormulaEvaluator({}, _formula, self).evaluate()
				self.skill_points[cat_id] += points_gained

			flag_modified(self, 'skill_points')

		self.add()
开发者ID:the-tosh,项目名称:boardless-open,代码行数:28,代码来源:models.py

示例5: accept_reservation

def accept_reservation(self, request):
    if not self.data or not self.data.get('accepted'):
        collection = ResourceCollection(request.app.libres_context)
        resource = collection.by_id(self.resource)
        scheduler = resource.get_scheduler(request.app.libres_context)
        reservations = scheduler.reservations_by_token(self.token)

        send_html_mail(
            request=request,
            template='mail_reservation_accepted.pt',
            subject=_("Your reservation was accepted"),
            receivers=(self.email, ),
            content={
                'model': self,
                'resource': resource,
                'reservations': reservations
            }
        )

        for reservation in reservations:
            reservation.data = reservation.data or {}
            reservation.data['accepted'] = True

            # libres does not automatically detect changes yet
            flag_modified(reservation, 'data')

        request.success(_("The reservation was accepted"))
    else:
        request.warning(_("The reservation has already been accepted"))

    return morepath.redirect(request.params['return-to'])
开发者ID:i18nHub,项目名称:onegov.town,代码行数:31,代码来源:reservation.py

示例6: update

    def update(self, instance, log=True, modified_attrs=(),
               validate_global=False):
        """Add `instance` to the DB session, and attempt to commit

        :param instance: Instance to be updated in the DB
        :param log: Should the update message be logged
        :param modified_attrs: Names of attributes that have been modified.
                               This is only required for some nested
                               attributes (e.g. when sub-keys of a runtime
                               properties dict that have been modified).
                               If DB updates aren't happening but no errors
                               are reported then you probably need this.
        :param validate_global: Verify that modification of this global
                                resource is permitted
        :return: The updated instance
        """
        if instance.is_resource and validate_global:
            validate_global_modification(instance)
        if log:
            current_app.logger.debug('Update {0}'.format(instance))
        db.session.add(instance)
        self._validate_unique_resource_id_per_tenant(instance)
        for attr in modified_attrs:
            flag_modified(instance, attr)
        self._safe_commit()
        return instance
开发者ID:cloudify-cosmo,项目名称:cloudify-manager,代码行数:26,代码来源:storage_manager.py

示例7: update_model

    def update_model(self, model_ins, new_data, overwrite=False):
        '''Updates a SQLAlchemy model instance with a dict object.
        If a key's item is a list or dict the attribute will
        be marked as changed.

        :param models: SQLAlchemy instance
        :param new_data: dict
        :param overwrite: boolean
        '''
        try:
            for key in new_data:
                if not hasattr(model_ins, key):
                    continue
                if isinstance(new_data[key], dict) and not overwrite:
                    getattr(model_ins, key).update(new_data[key])
                    flag_modified(model_ins, key)
                elif isinstance(new_data[key], list) and not overwrite:
                    setattr(model_ins, key, 
                        list(set(
                            getattr(model_ins, key) + new_data[key]
                        ))
                    )
                    flag_modified(model_ins, key)
                else:
                    setattr(model_ins, key, new_data[key])
        except Exception as e:
            raise TypeError(
                'Update model failed for the following key: {} with error: {}'.format(
                    key, 
                    e.message,
                )
            )
开发者ID:thomaserlang,项目名称:seplis,代码行数:32,代码来源:base.py

示例8: proc

    def proc(record):
        try:
            if 'authors' not in record.json:
                error('no authors for record %s' % record.json['control_number'])
                return

            for author_index, author_data in enumerate(record.json['authors']):
                if 'affiliations' not in author_data:
                    error('no affiliations for record %s' % record.json['control_number'])
                    continue

                for aff_index, aff_data in enumerate(author_data['affiliations']):
                    counts['all'] += 1

                    new_country = find_country(aff_data['value'])
                    if aff_data['country'] != new_country:
                        counts['changed'] += 1

                        info('Changed country for record with id %s from %s to %s' % (record.json['control_number'],
                                                                                      aff_data['country'], new_country))
                        record.json['authors'][author_index]['affiliations'][aff_index]['country'] = new_country

            if not dry_run:
                flag_modified(record, 'json')
        except Exception as e:
            error(str(e))
开发者ID:SCOAP3,项目名称:scoap3-next,代码行数:26,代码来源:cli_fixes.py

示例9: update_email_log_state

def update_email_log_state(log_entry, failed=False):
    if failed:
        log_entry.data['state'] = 'failed'
    else:
        log_entry.data['state'] = 'sent'
        log_entry.data['sent_dt'] = now_utc(False).isoformat()
    flag_modified(log_entry, 'data')
开发者ID:ThiefMaster,项目名称:indico,代码行数:7,代码来源:emails.py

示例10: post

    def post(self):
        i = request.form
        archive_id = i.get('archive_id')
        name = i.get('name')
        desc = i.get('description')

        try:
            b = api.Book.get(archive_id=archive_id)
        except:
            b = api.Book(archive_id=archive_id)
            b.create()

        author_ids = i.get('aids')
        if author_ids:
            author_ids = [a.strip() for a in author_ids.split(',')]
            for aid in author_ids:
                b.authors.append(api.Author.get(aid))
        if name:
            b.name = name
        if desc:
            from sqlalchemy.orm.attributes import flag_modified
            b.data[u'description'] = desc
            flag_modified(b, 'data')
        b.save()
        return b.dict()
开发者ID:emijrp,项目名称:books.archivelab.org,代码行数:25,代码来源:endpoints.py

示例11: _update_metadata

    def _update_metadata(self, **options):
        """ Updates the underlying metadata with the give values. This
        operats on low-level interfaces of Depot and assumes local storage.

        You should have a good reason for using this.

        """
        assert set(options.keys()).issubset({'content_type', 'filename'})

        if not hasattr(self.reference.file, '_metadata_path'):
            raise NotImplementedError(
                "The current depot storage backend does not support "
                "in-place metadata updates"
            )

        path = Path(self.reference.file._metadata_path)

        # store the pending metadata on the session to commit them later
        session = object_session(self)

        if 'pending_metadata_changes' not in session.info:
            session.info['pending_metadata_changes'] = []

        # only support upating existing values - do not create new ones
        for key, value in options.items():
            session.info['pending_metadata_changes'].append((path, key, value))

        # make sure we cause a commit here
        flag_modified(self, 'reference')
开发者ID:OneGov,项目名称:onegov.file,代码行数:29,代码来源:file.py

示例12: update_model

    def update_model(self, entity, instance):
        """ Update an instance from entity dict by merging the fields

        - Properties are copied over
        - JSON dicts are shallowly merged

        :param entity: Entity dict
        :type entity: dict
        :param instance: The instance to update
        :type instance: sqlalchemy.ext.declarative.DeclarativeMeta
        :return: New instance, updated
        :rtype: sqlalchemy.ext.declarative.DeclarativeMeta
        :raises AssertionError: validation errors
        """
        assert isinstance(entity, dict), 'Update model: entity should be a dict'

        # Check columns
        unk_cols = self.check_columns(entity.keys())
        assert not unk_cols, 'Update model: unknown fields: {}'.format(unk_cols)

        # Update
        for name, val in entity.items():
            if isinstance(val, dict) and self.mongomodel.model_bag.columns.is_column_json(name):
                # JSON column with a dict: do a shallow merge
                getattr(instance, name).update(val)
                # Tell SqlAlchemy that a mutable collection was updated
                flag_modified(instance, name)
            else:
                # Other columns: just assign
                setattr(instance, name, val)

        # Finish
        return instance
开发者ID:RussellLuo,项目名称:py-mongosql,代码行数:33,代码来源:crud.py

示例13: update_data_association

    def update_data_association(self, event, vc_room, event_vc_room, data):
        super(DummyPlugin, self).update_data_association(event, vc_room, event_vc_room, data)
        event_vc_room.data.update({key: data.pop(key) for key in [
            'show_phone_numbers'
        ]})

        flag_modified(event_vc_room, 'data')
开发者ID:florv,项目名称:indico-plugins,代码行数:7,代码来源:plugin.py

示例14: _update_uid_resync_status

    def _update_uid_resync_status(self, uid=None, status=None):
        # Helper function to make it easier to update resync data.
        with session_scope(self.namespace_id) as db_session:
            account = db_session.query(Account).options(
                load_only('_sync_status')).get(self.account_id)

            folder_id = str(self.folder_id)

            if 's3_resync_status' not in account._sync_status:
                account._sync_status['s3_resync_status'] = {}

            s3_resync_status = account._sync_status.get('s3_resync_status')

            if folder_id not in s3_resync_status:
                s3_resync_status[folder_id] = {}

            if uid is not None:
                s3_resync_status[folder_id]['last_synced_uid'] = uid

            if status is not None:
                s3_resync_status[folder_id]['status'] = status

            # We need to do this because SQLAlchemy doesn't pick up updates
            # to the fields of a MutableDict.
            flag_modified(account, '_sync_status')

            db_session.commit()
开发者ID:DrMoriarty,项目名称:sync-engine,代码行数:27,代码来源:s3.py

示例15: downgrade

def downgrade(pyramid_env):
    with context.begin_transaction():
        op.add_column(
            'agent_email_account',
            sa.Column("preferred", sa.SmallInteger,
                      default=False, server_default='0'))
    # Do stuff with the app's models here.
    from assembl import models as m
    db = m.get_session_maker()()

    with transaction.manager:
        # get from previous values
        db.execute("""UPDATE agent_email_account SET preferred=(
            SELECT abstract_agent_account.preferred
            FROM abstract_agent_account
            WHERE abstract_agent_account.id = agent_email_account.id
            AND abstract_agent_account."type" = 'agent_email_account')""")
        # Force update, transaction manager saw nothing
        aaa = db.query(m.Role).first()
        flag_modified(aaa, 'name')

    with context.begin_transaction():
        db.execute('ALTER TABLE agent_email_account ADD CHECK (preferred IN (0, 1))')
        op.drop_column(
            'abstract_agent_account', "preferred")
开发者ID:Lornz-,项目名称:assembl,代码行数:25,代码来源:45cf6094ba3d_preferred_abstractagentaccount.py


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