• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python attributes.flag_modified函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: commit

    def commit(self):
        """Store changes on current instance in database.

        Procedure followed:

        #. The signal :data:`invenio_records.signals.before_record_insert` is
            called with the record as function parameter.

        #. The record data is validate.

        #. The record is committed to the database.

        #. The signal :data:`invenio_records.signals.after_record_insert` is
            called with the record as function parameter.

        :returns: The Record instance.
        """
        if self.model is None or self.model.json is None:
            raise MissingModelError()

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

            self.validate()

            self.model.json = dict(self)
            flag_modified(self.model, 'json')

            db.session.merge(self.model)

        after_record_update.send(self)
        return self
开发者ID:hachreak,项目名称:invenio-records,代码行数:32,代码来源:api.py


示例17: meta

 def meta(self, meta):
     if isinstance(meta, Metadata):
         self.content_hash = meta.content_hash
         self.foreign_id = meta.foreign_id
         meta = meta.data
     self._meta = meta
     flag_modified(self, '_meta')
开发者ID:DavidLemayian,项目名称:aleph,代码行数:7,代码来源:document.py


示例18: update_data_vc_room

    def update_data_vc_room(self, vc_room, data):
        super(VidyoPlugin, self).update_data_vc_room(vc_room, data)

        for key in ['description', 'owner', 'room_pin', 'moderation_pin', 'auto_mute']:
            if key in data:
                vc_room.data[key] = data.pop(key)

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


示例19: update_model_with_json

def update_model_with_json(model):
    # Needed for JSON fields, see https://bashelton.com/2014/03/updating-postgresql-json-fields-via-sqlalchemy/
    mapper = object_mapper(model)
    for column in mapper.columns.values():
        if isinstance(column.type, JSON):
            flag_modified(model, column.name)
    
    db.session.add(model)
开发者ID:digideskio,项目名称:puffin,代码行数:8,代码来源:db.py


示例20: run

 def run(self, failed_migration=None, verbose=None):
     """Run the upgrade."""
     if not self.loaded:
         self.load()
     alembic = current_app.extensions['invenio-db'].alembic
     migration = Migration(
         version = self.dst_version,
         data = dict(steps=[], error=None, status='start')
     )
     # save the migration state
     if db.engine.dialect.has_table(db.engine, 'b2share_migrations'):
         db.session.add(migration)
         db.session.commit()
     for step in self.steps:
         step_log = dict(
             name=step.run.__name__,
             status='start'
         )
         migration.data['steps'].append(step_log)
         try:
             alembic.migration_context.bind.close()
             if step.condition is None or step.condition(alembic,
                                                         failed_migration):
                 if verbose:
                     click.secho(step.run.__doc__, fg='green')
                 step.run(alembic, verbose)
                 step_log['status'] = 'success'
             else:
                 step_log['status'] = 'skip'
         except BaseException as e:
             db.session.rollback()
             migration.data['steps'].append(dict(
                 name=step.run.__name__,
                 status='error'
             ))
             migration.data['error'] = traceback.format_exc()
             migration.data['status'] = 'error'
             if not db.engine.dialect.has_table(db.engine,
                                                'b2share_migrations'):
                 click.secho(
                     'Failed to upgrade while running upgrade {0} -> {1}. '
                     'Step {2}.\nTraceback:\n{3}'.format(
                         self.src_version, self.dst_version,
                         step.run.__name__, traceback.format_exc())
                 )
             raise e
         finally:
             # save the migration state
             if db.engine.dialect.has_table(db.engine,
                                            'b2share_migrations'):
                 flag_modified(migration, 'data')
                 db.session.add(migration)
                 db.session.commit()
     # mark the migration as successful and save it
     migration.data['status'] = 'success'
     db.session.add(migration)
     flag_modified(migration, 'data')
     db.session.commit()
开发者ID:EUDAT-B2SHARE,项目名称:b2share,代码行数:58,代码来源:api.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python attributes.get_history函数代码示例发布时间:2022-05-27
下一篇:
Python orm.Session类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap